|
Exactly why I made my comment. You should not try to write to a single file in a multi-user application; it makes no sense.
|
|
|
|
|
AndroidVH wrote: one `JSON` file in the `PHP` server to collect the orders from different customers Unlike an ASP or PHP page, a JSON file does not "collect" anything. Based on what you've provided, unless you are doing something totally wrong, there should be no way for it to become locked. If multiple clients request the same JSON file, the web server will deliver the file to each client without issue.
AndroidVH wrote:
Any suggestion? The whole "upload a file containing a customer number and/or order" approach seems way wrong to me.
When you make contact with a web server, a one-on-one relationship has been established. When you interact with a web page (e.g., PHP file), you are doing so with your "copy" of it. If some other client is also interacting with that same page, again it's on their own "copy" of it. The web server keeps track of all those connections (up to some upper limit).
Admittedly, I may be completely wrong on this. It borders on ecommerce which I have zero experience with. But what you are doing just seems kludgy and prone to error.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Sorry, I meant the orders are stored in the JSON by PHP code
I changed the process so as to prevent writing to the same file by different clients
|
|
|
|
|
I have to record a live audio/vedio and convert it into udp packets and broadcast it over wifi but not working after recording.
This is my code
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
random = new Random();
startAudioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkPermission()) {
audioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/" + createRandomFile(5) + "Recording.3gp";
mediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
startListener();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
startAudioButton.setEnabled(false);
stopAudioButton.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording Started ", Toast.LENGTH_SHORT).show();
}else{
requestPermission();
}
}
});
stopAudioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Recording Completed",Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
stopAudioButton.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
stopAudioButton.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
Toast.makeText(getApplicationContext(),"Recording Completed",Toast.LENGTH_SHORT).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) throws IllegalArgumentException,
SecurityException, IllegalStateException {
try{
startAudioButton.setEnabled(false);
stopAudioButton.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(audioSavePathInDevice);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(getApplicationContext(),"Recording Playing",Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopAudioButton.setEnabled(false);
stopAudioButton.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
mediaRecorderReady();
}
}
});
}
private void init() {
startAudioButton = ( Button)findViewById(R.id.button);
stopAudioButton = ( Button)findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button) findViewById(R.id.button4);
stopAudioButton.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
}
private void mediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(audioSavePathInDevice);
}
private String createRandomFile(int i) {
StringBuilder stringBuilder = new StringBuilder( i );
int j =0;
while (j<i){
stringbuilder.append(randomaudiofilename.charat(random.nextint(randomaudiofilename.length())));
="" j++;
="" }
="" return="" stringbuilder.tostring();
="" }
="" private="" void="" startlistener()="" {
="" create="" listener="" thread
="" listen="true;
" thread="" listenthread="new" thread(new="" runnable()="" {
="" <a="" href="https://www.codeproject.com/Members/override">@Override
public void run() {
try {
Log.i(LOG_TAG, "Listener started!");
DatagramSocket socket = new DatagramSocket(BROADCAST_PORT);
byte[] buffer = new byte[BUF_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, BUF_SIZE);
while(LISTEN) {
try {
socket.send(packet);
Log.i(LOG_TAG, "Listening for packets");
socket.receive(packet);
String data = new String(buffer, 0, packet.getLength());
Log.i(LOG_TAG, "Packet received from "+ packet.getAddress() +" with contents: " + data);
// String action = data.substring(0, 4);
}
catch(SocketTimeoutException e) {
if(!IN_CALL) {
Log.i(LOG_TAG, "No reply from contact. Ending call");
endCall();
return;
}
}
catch(IOException e) {
}
}
Log.i(LOG_TAG, "Listener ending");
socket.disconnect();
socket.close();
return;
}
catch(SocketException e) {
Log.e(LOG_TAG, "SocketException in Listener");
endCall();
}
}
});
listenThread.start();
}
private void stopListener() {
// Ends the listener thread
LISTEN = false;
}
private void endCall() {
// Ends the chat sessions
stopListener();
if(IN_CALL) {
call.endCall();
}
finish();
}
}
When i am using only MediaRecorder for recording it working but when i try for udp packet conversion it not ,basically not getting how to club recording and udp packet code.
modified 22-Jun-18 5:26am.
|
|
|
|
|
What does "not working" mean? Please format your code properly (and remove any lines not related to the problem), and give some useful details as to the actual problem.
|
|
|
|
|
I was trying to fetch JSON data into a RecyclerView using Retrofit 2. I also implemented pagination. Now for testing, I changed the JSON URL as if it will only show `5`items per page. The page number can be changed by adding "&page=`PAGE#`" at the end of the JSON URL (where PAGE# is integer value starting from 1 and if no Page no is mentioned, it will show by default the first page).
Problem: I have successfully added every page into the Recyclerview. But, it is adding the last page items twice, sometimes it is adding 3 times. Like this.
I am unable to find the problem. The step by step debugging does not help. Please help me. I am learning these so if you help me I would really appreciate it.
The JSON looks as follows:
[{
"id": 369,
"guid": {
"rendered": "URL?p=369"
},
"title": {
"rendered": "Shudder"
},
"content": {
"rendered": "<p>Shaking of body caused by fear.</p>\n<p>ভয়ের কাঁপুনি</p>\n<p> </p>\n",
"protected": false
},
"post_categories": [
"English",
"Father's Help",
"Madhyamik",
"Prose",
"Seen",
"Word Nest"
]
},
{
"id": 548,
"guid": {
"rendered": "URL?p=548"
},
"title": {
"rendered": "Swami went ______ school feeling that he was ______ worst boy ______ earth."
},
"content": {
"rendered": "<p>Swami went to school feeling that he was the worst boy on earth.</p>\n",
"protected": false
},
"post_categories": [
"Articles and Prepositions",
"English",
"Grammar",
"Madhyamik"
]
},
{
"id": 528,
"guid": {
"rendered": "URL?p=528"
},
"title": {
"rendered": "Teacher said "Explain the law of gravitation"."
},
"content": {
"rendered": "<p>Teacher ordered to explain the law of gravitation.</p>\n",
"protected": false
},
"post_categories": [
"English",
"Grammar",
"Madhyamik",
"Narration"
]
},
{
"id": 552,
"guid": {
"rendered": "URL?p=552"
},
"title": {
"rendered": "Test Post "Image""
},
"content": {
"rendered": "<p><img src=\"http://latex.codecogs.com/gif.latex?x^{2}+2xy+y^{2}&space;=&space;45\" alt=\"x^{2}+2xy+y^{2} = 45\" align=\"absmiddle\" /></p>\n<p> </p>\n<p><img src=\"http://aseducationsolution.com/wp-content/uploads/2018/06/blur-1868068_1920-150x150.jpg\" alt=\"\" width=\"150\" height=\"150\" class=\"alignnone wp-image-312 size-thumbnail\" /></p>\n<p> </p>\n<p>let us take <img src=\"http://latex.codecogs.com/gif.latex?\\inline&space;\\fn_cm&space;\\small&space;\\left&space;(&space;a+b&space;\\right&space;)^{3}&space;+&space;\\alpha&space;\\lambda&space;\\varepsilon&space;\\Delta&space;ABC\" alt=\"\\inline \\fn_cm \\small \\left ( a+b \\right )^{3} + \\alpha \\lambda \\varepsilon \\Delta ABC\" align=\"absmiddle\" /></p>\n<p> </p>\n<p>another example <img src=\"http://latex.codecogs.com/gif.latex?\\inline&space;\\small&space;a^{3}+b^{3}&space;=&space;123\" alt=\"\\inline \\small a^{3}+b^{3} = 123\" align=\"absmiddle\" /> check alignment is correct or not.</p>\n<p> </p>\n<p><img src=\"http://latex.codecogs.com/svg.latex?\\dpi{120}&space;\\small&space;\\frac{a}{b}+2c\" alt=\"\\dpi{120} \\small \\frac{a}{b}+2c\" align=\"absmiddle\" /> SVG</p>\n<p><img src=\"http://latex.codecogs.com/gif.latex?\\dpi{120}&space;\\small&space;\\sum&space;a+b+c+....\" alt=\"\\dpi{120} \\small \\sum a+b+c+....\" align=\"absmiddle\" /> GIF</p>\n<p> </p>\n<p>Equation example</p>\n<p> </p>\n<p> </p>\n",
"protected": false
},
"post_categories": [
"English",
"Madhyamik"
]
},
{
"id": 514,
"guid": {
"rendered": "URL?p=514"
},
"title": {
"rendered": "Time when Swami complained of a headache _________?"
},
"content": {
"rendered": "<p>9 A.M.</p>\n",
"protected": false
},
"post_categories": [
"English",
"Father's Help",
"Fill in from Text",
"Madhyamik",
"Prose",
"Seen"
]
}
]
Now, when there are no posts available as per the PAGE# of JSON URL, it will show the following JSON:
{
"code": "rest_post_invalid_page_number",
"message": "The page number requested is larger than the number of pages available.",
"data": {
"status": 400
}
}
Now, if you look at my code for the fragment:
private RecyclerView recyclerView;
private ProgressBar progressBar;
private LinearLayoutManager mLayoutManager;
private ArrayList < Model > list;
private RecycleAdapter adapter;
private View rootView;
private int pageNo = 2;
ProgressBar progress;
public String url = RetrofitArrayAPI.baseURL + RetrofitArrayAPI.EngHomeKey;
public static List < WPPost > mListPost;
Boolean isScrolling = false;
int currentItems, scrolledItems, totalItems;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.search_englishhome, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.postList);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLayoutManager);
DividerItemDecoration itemDecor = new DividerItemDecoration(Objects.requireNonNull(getActivity()), mLayoutManager.getOrientation());
recyclerView.addItemDecoration(itemDecor);
list = new ArrayList < > ();
progress = (ProgressBar) rootView.findViewById(R.id.recyclerprogress);
progress.setVisibility(View.GONE);
adapter = new RecycleAdapter(list, getActivity());
recyclerView.setAdapter(adapter);
getRetrofit();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
currentItems = mLayoutManager.getChildCount();
totalItems = mLayoutManager.getItemCount();
scrolledItems = mLayoutManager.findFirstVisibleItemPosition();
if (isScrolling = (currentItems + scrolledItems == totalItems)) {
isScrolling = false;
url = RetrofitArrayAPI.baseURL + RetrofitArrayAPI.EngHomeKey + "&page=" + pageNo;
progress.setVisibility(View.VISIBLE);
if (mListPost != null) {
getRetrofit();
} else {
progress.setVisibility(View.GONE);
}
}
}
});
return rootView;
}
public void getRetrofit() {
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RetrofitArrayAPI.baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
final Call < List < WPPost >> call = service.getPostInfo(url);
call.enqueue(new Callback < List < WPPost >> () {
@Override
public void onResponse(Call < List < WPPost >> call, Response < List < WPPost >> response) {
Log.e("EnglishHome", "Response" + response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
if (response.body() != null) {
pageNo++;
for (int i = 0; i < response.body().size(); i++) {
String tempCode = response.body().get(i).getCode();
int tempID = response.body().get(i).getId();
String tempTitle = response.body().get(i).getTitle().getRendered();
tempTitle = tempTitle.replace(""", "\"");
tempTitle = tempTitle.replace(""", "\"");
String tempContent = response.body().get(i).getContent().getRendered();
List < String > catitemnames = response.body().get(i).getPostCategories();
catitemnames.remove("Madhyamik");
catitemnames.remove("English");
catitemnames.remove("Grammar");
catitemnames.remove("Seen");
catitemnames.remove("Prose");
catitemnames.remove("Poem");
String categorynames = catitemnames.toString();
categorynames = categorynames.substring(1, categorynames.length() - 1);
if (tempCode != null) {
response.body().clear();
list.clear();
isScrolling = false;
mListPost.clear();
return;
} else {
list.add(new Model(tempID, tempTitle, tempContent, categorynames));
}
}
mListPost.clear();
progress.setVisibility(View.GONE);
} else {
progress.setVisibility(View.GONE);
}
}
@Override
public void onFailure(Call < List < WPPost >> call, Throwable t) {
}
});
}
}
My RecyclerView Adapter looks like:
public class RecycleAdapter extends RecyclerView.Adapter {
private ArrayList < Model > dataset;
private Context mContext;
public RecycleAdapter(ArrayList < Model > mList, Context context) {
this.dataset = mList;
this.mContext = context;
}
public static class ListTypeViewHolder extends RecyclerView.ViewHolder {
TextView title, categories;
RelativeLayout relativeLayout;
ListTypeViewHolder(View itemView) {
super(itemView);
this.title = (TextView) itemView.findViewById(R.id.texttitlesofrv);
this.categories = (TextView) itemView.findViewById(R.id.textcategoryrv);
this.relativeLayout = (RelativeLayout) itemView.findViewById(R.id.recyclerrow);
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
return new ListTypeViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
final Model object = dataset.get(holder.getAdapterPosition());
((ListTypeViewHolder) holder).title.setText(object.title);
((ListTypeViewHolder) holder).categories.setText(object.categoriesnames);
((ListTypeViewHolder) holder).relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, FullPostView.class);
intent.putExtra("itemPosition", holder.getAdapterPosition());
intent.putExtra("postID", object.postid);
intent.putExtra("postTitle", object.title);
intent.putExtra("postContent", object.content);
mContext.startActivity(intent);
}
});
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return dataset.size();
}
}
WPPOST POJO:
public class WPPost {
@SerializedName("code")
@Expose
private String code;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("guid")
@Expose
private Guid guid;
@SerializedName("title")
@Expose
private Title title;
@SerializedName("content")
@Expose
private Content content;
@SerializedName("post_categories")
@Expose
private List < String > postCategories = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Guid getGuid() {
return guid;
}
public void setGuid(Guid guid) {
this.guid = guid;
}
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
public List < String > getPostCategories() {
return postCategories;
}
public void setPostCategories(List < String > postCategories) {
this.postCategories = postCategories;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
MODEL Class:
public class Model {
public int postid;
public String title;
public String content;
public String categoriesnames;
public Model(int mID, String mTitle, String mContent, String mCategorynames) {
this.postid = mID;
this.title = mTitle;
this.content = mContent;
this.categoriesnames = mCategorynames;
}
}
Thank you in advance.
|
|
|
|
|
Do I have the correct current version of Android Studio installed on my machine ?
When I follow the drop down menus: ...Help../..About... I see these words on my screen...
Quote: Android Studio 3.0.1 Build #AI-171.4443003, built on November 9th, 2017
JRE: 1.8.0-152-release-915-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 8.1 6.3
Is that correct for today ? November of last year ?
|
|
|
|
|
|
The latest version is
Android Studio 3.1.3
Build #AI-173.4819257, built on June 4, 2018
JRE: 1.8.0_152-release-1024-b02 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
I highly recommend downloading the new version. The performance boost it brings is epic.
|
|
|
|
|
You sir, are just plain cool. Thank you
|
|
|
|
|
Quote: I'm writing a program using bound service with Inter Process Communication(IPC). The goal is to send the generated data in a thread (DataExchange) from the service to the mainActivity, using Messenger and Hanler. When the data is placed in the message queue from run method, I'm unable to receive it in the activityHandler (mainActivity). fortunatly I can receive the data in the serviceHandler (Local communication), however when I try to send the same message from the serviceHandler (service) to activityHandler (mainActivity), I'm getting a FATAL EXCETION
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Messenger.send(android.os.Message)' on a null object reference
Someone please help
MainActivity
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int UPDATE = 2;
TextView textView;
Messenger activityMessenger;
boolean bound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R. id. textView);
Intent bindBtService = new Intent(this, BluetoothService.class);
bindService(bindBtService, serviceConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
activityMessenger = new Messenger(service);
bound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
unbindService(serviceConnection);
activityMessenger = null;
bound = false;
}
};
class activityHandler extends Handler{
@Override
public void handleMessage(Message msg) {
String received;
switch (msg.what){
case UPDATE:
received = msg.getData().getString("update");
Log.i(TAG, "From Run Method " + received);
textView.setText(received);
break;
default:
super.handleMessage(msg);
}
}
}
@Override
protected void onDestroy() {
unbindService(serviceConnection);
activityMessenger = null;
bound = false;
super.onDestroy();
}
}
Service
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import java.util.Random;
public class BluetoothService extends Service {
private static final String TAG = BluetoothService.class.getSimpleName();
private static final int SEND = 1;
private static final int UPDATE = 2;
private DataExchange dataExchange;
Messenger serviceMessenger = new Messenger(new ServiceHandler());
public BluetoothService() {
}
@Override
public void onCreate() {
super.onCreate();
dataExchange = new DataExchange(new ServiceHandler());
dataExchange.start();
}
@Override
public IBinder onBind(Intent intent) {
return serviceMessenger.getBinder();
}
class ServiceHandler extends Handler{
Messenger mess;
Message message;
String response = " ";
Bundle bundle = new Bundle();
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SEND:
response = msg.getData().getString("message");
Log.i(TAG, "Random Number: " + response );
message = Message.obtain(null, UPDATE);
bundle.putString("update", response);
message.setData(bundle);
try {
msg.replyTo.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
private class DataExchange extends Thread implements Runnable{
Handler serviceHandler;
public DataExchange(ServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
for (int i = 0; i < 100; i++){
String val = String.valueOf(i);
try {
Thread.sleep(1000);
Message msg = prepareMessage(val);
try {
serviceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Message prepareMessage(String string){
Bundle dataBundle = new Bundle();
Message result = serviceHandler.obtainMessage(SEND);
dataBundle.putString("message", string);
result.setData(dataBundle);
return result;
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.seber.lisah">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".BluetoothService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
|
|
|
|
|
I am guessing (since you did not bother to tell us) that the line that causes the exception is:
msg.replyTo.send(message);
which means that either msg or replyTo are not valid references. But only you can check that by using your debugger to step through the code.
|
|
|
|
|
Dear mr. MacCutchan Thank you very much for your answer, and yes your guess is correct Iam getting the exception on this line
msg.replyTo.send(message);
I am a novice on Android programming and I tried to debug the program. This is what I get from the debugger
this = {RuntimeInit$UncaughtHandler@4000}
t = {Thread@3564} "Thread[main,5,main]"
e = {NullPointerException@4001} "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Messenger.send(android.os.Message)' on a null object reference"
cause = {NullPointerException@4001} "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Messenger.send(android.os.Message)' on a null object reference"
detailMessage = "Attempt to invoke virtual method 'void android.os.Messenger.send(android.os.Message)' on a null object reference"
stackState = {Object[9]@4006}
stackTrace = {StackTraceElement[0]@4007}
suppressedExceptions = {Collections$EmptyList@4008} size = 0
shadow$_klass_ = {Class@2610} "class java.lang.NullPointerException"
shadow$_monitor_ = -2090121786
Quote: I've also tried to specify the handler directly like so:
Quote:
msg.replyTo = new Messenger(new ServiceHandler());
serviceMessenger.send(msg);
Quote: but I'm getting another exception on line serviceMessenger.send(msn);
java.lang.IllegalStateException: { when=0 what=1 target=com.seber.lisah.BluetoothService$ServiceHandler } This message is already in use.
|
|
|
|
|
You need to go back to the original error and find out why msg or replyTo are null. As I said earlier, we cannot diagnose the state of your objects. If nothing obvious shows up then you need to check the documentation to make sure that you are creating the objects correctly. Randomly changing the code before you have diagnosed the error is not likely to help you.
|
|
|
|
|
Member 11911065 wrote:
I am a novice on Android programming... Which is probably a good reason to start with a few simpler programs before diving into services and IPC programs. Tracking down null pointer exceptions is a fundamental task, so if that is giving you trouble, it's time to take a step (or two) back and get the basics nailed down real good.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Sir I have problem. Let suppose that I have data like 23,56,89,88,90,1234,3445. now I want to add them all and want to get result. but this code is giving me result like that 23+56+36=92 not 115. mean it make addition of just to previous values
Here is my code
**************
package com.example.maher.androidspinnertutorial;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class calculatr extends AppCompatActivity {
Button btn_1,btn_2,btn_3,btn_4,btn_5,btn_6,btn_7,btn_8,btn_9,btn_0,btn_Add,btn_Sub,btn_Mul,btn_Div,btn_calc,btn_dec,btn_clear;
EditText ed1;
float Value1, Value2;
boolean mAddition, mSubtract, mMultiplication, mDivision ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculatr);
btn_0 = (Button) findViewById(R.id.btn_0);
btn_1 = (Button) findViewById(R.id.btn_1);
btn_2 = (Button) findViewById(R.id.btn_2);
btn_3 = (Button) findViewById(R.id.btn_3);
btn_4 = (Button) findViewById(R.id.btn_4);
btn_5 = (Button) findViewById(R.id.btn_5);
btn_6 = (Button) findViewById(R.id.btn_6);
btn_7 = (Button) findViewById(R.id.btn_7);
btn_8 = (Button) findViewById(R.id.btn_8);
btn_9 = (Button) findViewById(R.id.btn_9);
btn_Add = (Button) findViewById(R.id.btn_Add);
btn_Div = (Button) findViewById(R.id.btn_Div);
btn_Sub = (Button) findViewById(R.id.btn_Sub);
btn_Mul = (Button) findViewById(R.id.btn_Mul);
btn_calc = (Button) findViewById(R.id.btn_calc);
btn_dec = (Button) findViewById(R.id.btn_dec);
btn_clear = (Button) findViewById(R.id.btn_clear);
ed1 = (EditText) findViewById(R.id.edText1);
btn_0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"0");
}
});
btn_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"1");
}
});
btn_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"2");
}
});
btn_3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"3");
}
});
btn_4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"4");
}
});
btn_5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"5");
}
});
btn_6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"6");
}
});
btn_7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"7");
}
});
btn_8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"8");
}
});
btn_9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+"9");
}
});
btn_dec.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+".");
}
});
btn_Add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Value1 = Float.parseFloat(ed1.getText() + "");
mAddition = true ;
ed1.setText(null);
}
});
btn_Sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Value1 = Float.parseFloat(ed1.getText() + "");
mSubtract = true ;
ed1.setText(null);
}
});
btn_Mul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Value1 = Float.parseFloat(ed1.getText() + "");
mMultiplication = true ;
ed1.setText(null);
}
});
btn_Div.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Value1 = Float.parseFloat(ed1.getText()+"");
mDivision = true ;
ed1.setText(null);
}
});
btn_calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Value2 = Float.parseFloat(ed1.getText() + "");
if (mAddition == true){
ed1.setText(Value1 + Value2 +"");
mAddition=false;
}
if (mSubtract == true){
ed1.setText(Value1 - Value2 +"");
mSubtract=false;
}
if (mMultiplication == true){
ed1.setText(Value1 * Value2 + "");
mMultiplication=false;
}
if (mDivision == true){
ed1.setText(Value1 / Value2+"");
mDivision=false;
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText("");
}
});
}
}
****************
could anyone help me please?/
|
|
|
|
|
You are treating each part of the calculation as the complete result, rather than saving the interim value. When you click the + button you set Value1 equal to the number in the txt box. But next time you press the + button you overwrite Value1. So typing 23+56+36 actually only gives the result of 56+36, which is 92. You need to keep a running total as each operator button is pressed. So the sequence should be something like:
Set Value1 to zero
set next operator to +
DO
if an operator button is pressed
if it is the '=' operator
display the result
else
parse the text into the number
apply the current operation to Value1 (i.e add, subtract etc. this number to Value1)
set the 'next' operator to the pressed button
WHILE operator is not '='
|
|
|
|
|
Hi, my name is Mustafa. I am from Turkey.
I do not know your language, so I'm getting help from Google Translate.
Sample code on Windows Visual Basic.
İF WebBrowser.DocumentText.Contains("404")
MsgBox("This page can not be reached.")
I want to implement this code in xamarin WebView as well. How do I do that?
I've been searching from here. This is sample code. but I'm getting an error
|
|
|
|
|
What EXACTLY are you needing help with? Do you have an Android app that is using a WebView control and you are wanting to know if a requested page could not be loaded, or do you need help displaying a "message box" to the user?
If the former, call setWebViewClient() on your WebView object and listen for the 404 error in the onReceivedError() method.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
First of all thank you for your response.
I want to search for a post on the Web page.I want to tell you what I want to tell you with Picture.
http://anadolufilms.com.tr.ht/ocean/1.png
http://anadolufilms.com.tr.ht/ocean/2.png
That's what I want to do How is this done with Xamarin WebView?
|
|
|
|
|
I see code, so what is, or isn't, working for you?
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Since android code is visible for attackers, I want to change the name of variables and functions
I know there are some tools for android obfuscation but I want to add more security
I think I should have an excel file with 2 columns (1 - unique old names 2 - unique new names)
Then utilizing a tool replace the old names with the new ones
Any suggestion?
|
|
|
|
|
Replacing meaningful names by something else makes code not more secure. It makes it just a little bit harder to reproduce what the code is doing.
Recommended read: Security through obscurity - Wikipedia[^] and other sources about that term.
If you really want to do it:
Because source code files are text files, it is a job for simple search & replace which can be automated using regular expressions iterating over the values of an input file (CSV would be better / simpler to use than Excel) and a list of source files. With Linux I would use a shell script for all the stuff except the replace which can be done with sed.
|
|
|
|
|
|
The tools are provided by the console (PowerShell with Windows, bash with Linux). They are able to iterate over files in a directory (with an optional search mask and optionally including sub directories). You can even read column separated text files there line by line and use that data to perform the replacement (executing sed with Linux or again PowerShell commands with Windows).
|
|
|
|
|