Make sure that activity starts after execution of async task - android

I want to make sure that my activity starts after execution of async task. As of now it gets started before the async task completes in background
This is where new activity is called. Before calling the new activity i am calling PagerAsyncTask. I want to make sure that new activity is called only after successful completion of PagerAsyncTask.
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PagerAsyncTask().execute();
sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("hasadd", false);
editor.commit();
Log.e("hi", "dsscdds");
startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));
PagerAsyncTask
class PagerAsyncTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb=null;
BufferedReader reader=null;
String serverResponse=null;
try {
URL url = new URL("https://enigmatic-woodland-35608.herokuapp.com/pager.json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
int statusCode = connection.getResponseCode();
//Log.e("statusCode", "" + statusCode);
if (statusCode == 200) {
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
connection.disconnect();
if (sb!=null)
serverResponse=sb.toString();
Log.e("haha", serverResponse);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return serverResponse;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//All your UI operation can be performed here
//Response string can be converted to JSONObject/JSONArray like
try {
//String mr[] = new String[5];
JSONObject response=new JSONObject(s);
Iterator<?> keys = response.keys();
int i=0;
while( keys.hasNext() ) {
String key = (String)keys.next();
Log.e("hi",key);
Log.e("hey",response.getString(key));
// mr[i]=response.getString(key);
// Log.e("e=",mr[i]);
i++;
}
Log.e("I", String.valueOf(i));
Iterator<?> keys1 = response.keys();
mr = new String[i];
int k=0;
while ( keys1.hasNext() )
{
String key = (String)keys1.next();
mr[k++]=response.getString(key);
Log.e("fdvfd",mr[k-1]);
}
for (int j=0;j<mr.length;j++)
{
Log.e("dsd",mr[j]);
}
isComplete=true;
setMr(mr);
setSet(1);
new RestaurantFragment().setmResources(mr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

There are a couple of ways to do this
1) use startActivity inside onPostExecute()
2)Pass activity reference to Async task and call some function in the activity from onPostExecute as show here
3)pass a function callback to AsyncTask as shown here. Though this is unnecessarily complicated for your task

You need to move the startActivity to the postExecute of the AsyncTask.
Your onCreate without the startActivity:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PagerAsyncTask().execute();
sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("hasadd", false);
editor.commit();
Log.e("hi", "dsscdds");
The PagerAsyncTask onPostExecute:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//All your UI operation can be performed here
//Response string can be converted to JSONObject/JSONArray like
try {
JSONObject response=new JSONObject(s);
Iterator<?> keys = response.keys();
int i=0;
while( keys.hasNext() ) {
String key = (String)keys.next();
Log.e("hi",key);
Log.e("hey",response.getString(key));|
i++;
}
Log.e("I", String.valueOf(i));
Iterator<?> keys1 = response.keys();
mr = new String[i];
int k=0;
while ( keys1.hasNext() )
{
String key = (String)keys1.next();
mr[k++]=response.getString(key);
Log.e("fdvfd",mr[k-1]);
}
for (int j=0;j<mr.length;j++)
{
Log.e("dsd",mr[j]);
}
isComplete=true;
setMr(mr);
setSet(1);
new RestaurantFragment().setmResources(mr);
startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
Also, the code new RestaurantFragment().setmResources(mr); probably does nothing, since you are not attaching the fragment to anywhere

Related

arraymap is better than sparse array to memorise some data catched from a JSON file?

I had wrote a code which use a parse to catch some data from a JSON file but i don't know what kind of structure is better between the sparse array or the array map for memorise these data ?
I had used a array map but I don't know if it's too wasted on so little data data.
public class MainActivity extends AppCompatActivity {
private ProgressDialog pd;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, ValoriDiSueg> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
The parse of these data
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("weather"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new ValoriDiSueg( jsonPart.getString("main"), jsonPart.getString("description")));
//ArrayDati.put(i,new ValoriDiSueg("description : "+ jsonPart.getString("description")));
textViewProg.setText(textViewProg.getText()+"main : "+ ArrayDati.get(i).Main +"\n"+textViewProg.getText()+"description : "+ ArrayDati.get(i).Description );
}
} catch (Exception e ){
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
}
And I created a class:
public class ValoriDiSueg {
String Main;
String Description;
public ValoriDiSueg(String main, String description) {
this.Main = main;
this.Description = description;
}
}
any suggestions??
In simple:
If your key is int or long, you should use SparseArray, SparseLongArray as it will not boxing/un-boxing the key value when operates. Also, it provides similar classes for int/long values as long as the key is int/long.
If you key is not int nor long, such as an object or String, you should use ArrayMap instead as it will handle the conflicts of key hashes.
There are no much performance and memory usage difference between these two class as they are all requires O(log n) to search and O(n) to insert/delete (in most cases).

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

Android Duplicate list view due to onResume

Hello I'm new at android. There is a arrayList and a ListView. I used AsyncTask class to invoke the database from MYSQL DB. This AsyncTask class sets mArrayList(this is the arrayList). To update the list view when I return from another activity, I used onResume(). This is the part.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mold_breakage_history);
brokenMoldListView = findViewById(R.id.brokenMoldListView);
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
}
#Override
protected void onResume() {
super.onResume();
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
In onResume(), I initialized the mArrayList and invoke AsyncTask again to update ListView. The problem is when this activity was first executed, the ListView was duplicated. But, when I back from next page of this Activity, the problem is disappeared. I hope that this issue is not present when activity is first executed. Please help.
This is code of AsyncTask class.
#SuppressLint("StaticFieldLeak")
private class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MoldBreakageHistoryActivity.this,
"Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Log.d(TAG, "response - " + result);
mJsonString = result;
showResult();
}
#Override
protected String doInBackground(String... params) {
String serverURL = params[0];
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.connect();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "InsertData: Error ", e);
errorString = e.toString();
return null;
}
}
}
private void showResult() {
try {
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
String brokenDate = item.getString(TAG_BROKEN_DATE);
String moldCode = item.getString(TAG_MOLD_CODE);
String finalHitting = item.getString(TAG_FINAL_HITTING_TIMES);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(TAG_BROKEN_DATE, brokenDate);
hashMap.put(TAG_MOLD_CODE, moldCode);
hashMap.put(TAG_FINAL_HITTING_TIMES, finalHitting);
mArrayList.add(hashMap);
}
ListAdapter adapter = new SimpleAdapter(
MoldBreakageHistoryActivity.this, mArrayList, R.layout.list_item_broken_mold,
new String[]{TAG_BROKEN_DATE, TAG_MOLD_CODE, TAG_FINAL_HITTING_TIMES},
new int[]{R.id.brokenDateListItem, R.id.brokenMoldListItem, R.id.finalHittingTimesListItem}
);
brokenMoldListView.setAdapter(adapter);
} catch (JSONException e) {
Log.d(TAG, "showResult : ", e);
}
}
Remove this:
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
from onCreate. onResume is executed right after onCreate and your async task was executing twice, that's why it was duplicated in the first place. When you hit the back only the onResume was executed, so the problem would happen then.
please just remove
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
From your onCreate method. but, if you need to do som scenario in onCreate and other one in onResume you can use mArrayList.clear(); before execute the new task only.

while navigating to the next page from login page, blank screen appears

I have integrated a webservice and after integrating it goes to the next page.
But the problem is while navigating to from login page to next page, it is showing blank screen and I do not understand what's the problem.
Kindly Help!!
Thanks in advance.
Here is my code
public class Mobile_Number_Activity extends Activity {
private EditText ed_Mobile_Number;
private Button btnSubmit;
private TextView Hyperlink;
private ProgressDialog pDialog;
private JSONObject json;
private int success = 0;
private String path = "xxx";
private String strMobileNumber = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mobile_number);
ed_Mobile_Number = (EditText) findViewById(R.id.ed_Mobile_Number);
btnSubmit = (Button) findViewById(R.id.btn_mobile_submit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!ed_Mobile_Number.getText().toString().equals(""))
{
strMobileNumber = ed_Mobile_Number.getText().toString();
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
}
else
{
Toast.makeText(getApplicationContext(), "Please Enter Mobile Number", Toast.LENGTH_LONG).show();
}
}
});
}
Here is SendPost Request Class which extends Asyntask
public class SendPostRequest extends AsyncTask<String, Void, String> {
public static ProgressDialog pDialog;
private String path = "xxxx";
public String Mobile_Number = "";
private Context mContext;
public SendPostRequest(Context context)
{
this.mContext=context;
pDialog = new ProgressDialog(mContext);
pDialog.setTitle("Loading...");
pDialog.setMessage("Please wait...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
#Override
protected String doInBackground(String... arg0)
{
try
{
Thread.sleep(40000);
String m_number=arg0[0];
URL url = new URL(path); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", "data");
postDataParams.put("password", "data");
postDataParams.put("mobile", m_number);
System.out.println(m_number);
Mobile_Number=m_number;
Log.e("params", postDataParams.toString());
//conversion of 15 min to miliseconds :900000
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(1500/* milliseconds */);
//conn.setConnectTimeout(1500 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
if (pDialog != null && pDialog.isShowing()) {
//Toast.makeText(mContext.getApplicationContext(), result,Toast.LENGTH_LONG).show();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
String otp = jsonObject.optString("otp");
Log.d("otp value is", otp);
message(otp);
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while (itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
public void message(String otp)
{
Intent myIntent = new Intent(this.mContext,OTP_Code_Activity.class);
myIntent.putExtra("Mobile Number", Mobile_Number);
System.out.println(Mobile_Number);
myIntent.putExtra("OTP Code", otp);
mContext.startActivity(myIntent);
pDialog.dismiss();
}
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
Change this to activity context.
new SendPostRequest(Mobile_Number_Activity.this).execute(strMobileNumber);
Delete(uninstall) the app from your phone, and run it again..It happens due to some issues with database. Or else I think you haven't mention the activity in the Manifest
Change
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
To
new SendPostRequest(this).execute(strMobileNumber);
And with Application Context, you can't show Dialog. You need to use Activity instance.
Change
SendPostRequest(Context context)
To
SendPostRequest(Activity context)
It might be helpful. Check log and see have any error in JSON Parse Exception as well.

android jsonObject Null Pointer Exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am new to JSON. I need help. My android studio keeps on telling me that my jsonobject is NULL. I can parse and display my jsonarray into a listview. But when i click the page where i displayed it, my app crashes.
Parser
class BgTask extends AsyncTask<Void, Void, String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://10.0.2.2/result/hehe.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputstream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
}
}
public void publishGame(View view)
{
if(json_string == null)
{
Toast.makeText(getApplicationContext(), "Get Data First",Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(this, Games.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
}
code that posts
Bundle intent=getIntent().getExtras();
if(intent !=null) {
json_string = intent.getString("json_data");
json_string = getIntent().getExtras().getString("json_data");
}
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String team1, score1, team2, score2, Type;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
team1 = JO.getString("team1");
score1 = JO.getString("score1");
team2 = JO.getString("team2");
score2 = JO.getString("score2");
Type = JO.getString("Type");
Downloader downloader = new Downloader(team1, score1, team2, score2, Type);
gamesAdapter.add(downloader);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The error pointing is here try {
jsonObject = new JSONObject(json_string);
The error is because you are trying to parse "json_data" to JSONObject which is not a valid json. Perhaps you are having server response in a variable called json_data which is of String type if that is the case you need to pass that variable instead of passing String literal into JSONObject constructor.

Categories

Resources