Trying to generate an android listview from a json array - android

So I have the following code in my current activity class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chores);
bChore = (Button) findViewById(R.id.addChore);
bChore.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
final String user = extras.getString("username");
fillInBackground();
}
#Override
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
final String user = extras.getString("username");
switch (v.getId()) {
case R.id.addChore:
name = (EditText) findViewById(R.id.choreName);
value = (EditText) findViewById(R.id.points);
String choreTitle = name.getText().toString();
int pointValue = Integer.parseInt(value.getText().toString());
try {
if (choreTitle.length() <= 0)
Toast.makeText(Chores.this, "Please enter a chore", Toast.LENGTH_SHORT).show();
else {
if (pointValue == 0)
Toast.makeText(Chores.this, "Please enter a valid number", Toast.LENGTH_SHORT).show();
else {
Chore chore = new Chore(choreTitle, pointValue, user);
uploadChore(chore);
break;
}
}
} catch (NumberFormatException e) {
Toast.makeText(Chores.this, "Please enter a valid point value", Toast.LENGTH_SHORT).show();
}
}
}
private void fillInBackground() {
new AsyncTask<Void, Void, Wrapper>() {
Bundle extras = getIntent().getExtras();
final String user = extras.getString("username");
#Override
protected Wrapper doInBackground(Void... params) {
String requestURL = SERVER_ADDRESS + "FetchChoreData.php";
ListView choreList = (ListView) findViewById(R.id.choreList);
ArrayList<String> chores = new ArrayList<>();
Wrapper wrapper = new Wrapper();
String headings = "Chore" + "\t" + "Child" + "\t" + "Points";
chores.add(headings);
URL url;
try {
//Opens the connection to the PHP files
//Sets the conditions of the connection
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Opens an output stream to send the data to be verified
// and then closes the all output streams and flushes the output writer
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", user);
String query = builder.build().getEncodedQuery();
writer.write(query);
writer.flush();
writer.close();
os.close();
//saves the response code to ensure connection was succesful
int code = conn.getResponseCode();
Log.d("code", Integer.toString(code));
//Opens an input stream to retrieve verified data back from the server
//Starts a String Builder to read the data off the input
//Closes the BufferedReader once it has finished building the string
InputStream responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
stringBuilder.append(line + "/n");
responseStreamReader.close();
String response = stringBuilder.toString();
Log.d("response", response);
JSONObject jsonResponse = new JSONObject(response);
//Creates a JSON object from the string
JSONArray choresArray = jsonResponse.getJSONArray("chore");
for (int i = 0; i < choresArray.length(); i++) {
JSONObject chore = choresArray.getJSONObject(i);
String current_chore = chore.optString("chore_name");
String name = chore.optString("child_username");
String points = chore.optString("point_value");
String currentChore = "";
if (name == null)
currentChore = current_chore + "\t" + "Not Claimed" + "\t" + points;
else
currentChore = current_chore + "\t" + name + "\t" + points;
chores.add(currentChore);
Log.d("Output", currentChore);
}
wrapper.myArrayAdapter = new ArrayAdapter<>(Chores.this, android.R.layout.simple_list_item_1, chores);
wrapper.list = choreList;
} catch (Exception e) {
e.printStackTrace();
}
return wrapper;
}
protected void onPostExecute(Wrapper wrapper) {
//After the previous method executes we end the process dialog
//and we return the user call back and return the verified user
wrapper.list.setAdapter(wrapper.myArrayAdapter);
}
}.execute();
}
private void uploadChore(Chore chore) {
Bundle extras = getIntent().getExtras();
final String user = extras.getString("username");
//Implements the ServerRequest class to register the user details
ServerRequests serverRequests = new ServerRequests(this);
//Checks that the details are valid and what account type it is setting up
serverRequests.storeChoreData(chore,new GetUserCallBack() {
//What is done when the user has successfully registered
#Override
public void complete(User returnedUser) {
Intent chores = new Intent(Chores.this, Chores.class);
chores.putExtra("username", user);
startActivity(chores);
}
});
}
}
The wrapper class looks as follows:
public class Wrapper {
public ListView list;
public ArrayAdapter<String> myArrayAdapter;
}
However when I run the application it stops and I get the following fatal exception:
W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
03-14 11:54:17.493 18935-19311/com.jack.pointcollector W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
03-14 11:54:17.493 18935-19311/com.jack.pointcollector W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
03-14 11:54:17.493 18935-19311/com.jack.pointcollector W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at com.jack.pointcollector.Chores$1.doInBackground(Chores.java:149)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at com.jack.pointcollector.Chores$1.doInBackground(Chores.java:89)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
03-14 11:54:17.494 18935-19311/com.jack.pointcollector W/System.err: at java.lang.Thread.run(Thread.java:818)
03-14 11:54:17.581 18935-18935/com.jack.pointcollector D/AndroidRuntime: Shutting down VM
03-14 11:54:17.581 18935-18935/com.jack.pointcollector E/AndroidRuntime: FATAL EXCEPTION: main Process: com.jack.pointcollector, PID: 18935
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.jack.pointcollector.Chores$1.onPostExecute(Chores.java:183)
at com.jack.pointcollector.Chores$1.onPostExecute(Chores.java:89)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Could someone please tell me where I'm going wrong as I am only new to this.

the problem is only that your create the Object Wrapper in doInBackgroud() method........and you try to access then in onPostExecute() method.......
new AsyncTask<Void, Void, Wrapper>() {
#Override
protected Wrapper doInBackground(Void... params) {
ListView choreList = (ListView) findViewById(R.id.choreList);
ArrayList<String> chores = new ArrayList<>();
// change this make them Global.....
Wrapper wrapper = new Wrapper();
wrapper.myArrayAdapter = new ArrayAdapter<>(Chores.this, android.R.layout.simple_list_item_1, chores);
wrapper.list = choreList;
} catch (Exception e) {
e.printStackTrace();
}
return wrapper;
}
protected void onPostExecute(Wrapper wrapper) {
//After the previous method executes we end the process dialog
//and we return the user call back and return the verified user
wrapper.list.setAdapter(wrapper.myArrayAdapter);
}
}.execute();
}

You should move
ListView choreList = (ListView) findViewById(R.id.choreList);
ArrayList<String> chores = new ArrayList<>();
outside your do in background and have them as a globar variable.
Once you are done fetching data you can set your adapter in onPost execute. Your listview is never initialised and hence the null pointer exception.

String response = stringBuilder.toString();
JSONObject jsonResponse = new JSONObject(response);
check response
it should be like:
{
"chore": [{
"chore_name": "name",
"child_username": "username",
"point_value": "value"
}, {
"chore_name": "name",
"child_username": "username",
"point_value": "value"
}]
}

Reason:
Problem is not with setting adapter but with the JSON parsing. As per your error log
W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
you are getting as string which can not be converted to a JSONObject. When this error occurs the is being catch in the catch block and by that time
wrapper.myArrayAdapter = new ArrayAdapter<>(Chores.this, android.R.layout.simple_list_item_1, chores);
wrapper.list = choreList;
is not called. This is causing onPostExecute to receive a null object of listview and finally a NPE is being thrown.
Solution:
You should check the JSON you are getting form server and correct them.

Following are the mistakes I found in your code and I also tried to fix the same.
You should initialize all your views and adapter in onCreate().
In uploadChore()'s complete(), don't start the same activity for passing the data to some other method rather pass it as an argument.
The ListView and its Adapter should be initialized at the beginning. Later on, add the data into the list and call adapter's notifyDataSetChanged()
ArrayList<String> chores;
Wrapper wrapper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chores);
bChore = (Button) findViewById(R.id.addChore);
name = (EditText) findViewById(R.id.choreName);
value = (EditText) findViewById(R.id.points);
wrapper = new Wrapper();
ListView choreList = (ListView) findViewById(R.id.choreList);
chores = new ArrayList<>();
wrapper.myArrayAdapter = new ArrayAdapter<>(Chores.this, android.R.layout.simple_list_item_1, chores);
wrapper.list = choreList;
wrapper.list.setAdapter(wrapper.myArrayAdapter);
bChore.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
Bundle extras = getIntent().getExtras();
final String user = extras.getString("username");
switch (v.getId())
{
case R.id.addChore:
String choreTitle = name.getText().toString();
int pointValue = Integer.parseInt(value.getText().toString());
try
{
if (choreTitle.length() <= 0)
Toast.makeText(Chores.this, "Please enter a chore", Toast.LENGTH_SHORT).show();
else
{
if (pointValue == 0)
Toast.makeText(Chores.this, "Please enter a valid number", Toast.LENGTH_SHORT).show();
else
{
Chore chore = new Chore(choreTitle, pointValue, user);
uploadChore(chore);
break;
}
}
}
catch (NumberFormatException e)
{
Toast.makeText(Chores.this, "Please enter a valid point value", Toast.LENGTH_SHORT).show();
}
}
}
private void fillInBackground(String user)
{
new AsyncTask<Void, String, Wrapper>()
{
#Override
protected Wrapper doInBackground(Void... params)
{
String requestURL = SERVER_ADDRESS + "FetchChoreData.php";
String headings = "Chore" + "\t" + "Child" + "\t" + "Points";
publishProgress(headings);
URL url;
try
{
//Opens the connection to the PHP files
//Sets the conditions of the connection
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Opens an output stream to send the data to be verified
// and then closes the all output streams and flushes the output writer
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", user);
String query = builder.build().getEncodedQuery();
writer.write(query);
writer.flush();
writer.close();
os.close();
//saves the response code to ensure connection was succesful
int code = conn.getResponseCode();
Log.d("code", Integer.toString(code));
//Opens an input stream to retrieve verified data back from the server
//Starts a String Builder to read the data off the input
//Closes the BufferedReader once it has finished building the string
InputStream responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
stringBuilder.append(line + "/n");
responseStreamReader.close();
String response = stringBuilder.toString();
Log.d("response", response);
JSONObject jsonResponse = new JSONObject(response);
//Creates a JSON object from the string
JSONArray choresArray = jsonResponse.getJSONArray("chore");
for (int i = 0; i < choresArray.length(); i++)
{
JSONObject chore = choresArray.getJSONObject(i);
String current_chore = chore.optString("chore_name");
String name = chore.optString("child_username");
String points = chore.optString("point_value");
String currentChore = "";
if (name == null)
currentChore = current_chore + "\t" + "Not Claimed" + "\t" + points;
else
currentChore = current_chore + "\t" + name + "\t" + points;
publishProgress(currentChore);
Log.d("Output", currentChore);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return wrapper;
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
wrapper.list.add(values[0]);
}
protected void onPostExecute(Wrapper wrapper)
{
//After the previous method executes we end the process dialog
//and we return the user call back and return the verified user
wrapper.myArrayAdapter.notifyDataSetChanged();
}
}.execute();
}
private void uploadChore(Chore chore)
{
Bundle extras = getIntent().getExtras();
final String user = extras.getString("username");
//Implements the ServerRequest class to register the user details
ServerRequests serverRequests = new ServerRequests(this);
//Checks that the details are valid and what account type it is setting up
serverRequests.storeChoreData(chore, new GetUserCallBack()
{
//What is done when the user has successfully registered
#Override
public void complete(User returnedUser)
{
// Simple add data into the list. Don't start same activity again and again.
fillInBackground(user);
}
});
}

Related

How do I show result from server response to app in Android?

I am developing and I want to show user login or not. Following is my code in this it shows correct response in Logcat but not show the message on app side(i.e login success or login failed message). How do I do this?
How do I parse json data in this?
Please suggest me!!
// Following is response from server shows inside Logcat
{
"login": [
{
"sessionid": 12973,
"responsetypes": "success"
}
]
}
// Following is my code
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendGetReqButton;
TextView tv_forgot;
Button register;
Toolbar toolbar;
private boolean loggedIn = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
tv_forgot= (TextView)findViewById(R.id.tv_forgot);
tv_forgot.setOnClickListener(this);
usernameEditText = (EditText) findViewById(R.id.ed_email);
passwordEditText = (EditText) findViewById(R.id.ed_passowrd);
register = (Button) findViewById(R.id.btn_reg);
sendGetReqButton = (Button) findViewById(R.id.btn_login);
sendGetReqButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_login){
// Get the values given in EditText fields
String userID = usernameEditText.getText().toString();
String password = passwordEditText.getText().toString();
System.out.println("Givennames is :" + userID + " Given password is :" + password);
// Pass those values to connectWithHttpGet() method
connectWithHttpGet(userID, password);
}
else {
Toast.makeText(LoginActivity.this, "Please Fill the fields", Toast.LENGTH_LONG).show();
}
}
private void connectWithHttpGet(String userID, String password) {
// Connect with a server is a time consuming process.
//Therefore we use AsyncTask to handle it
// From the three generic types;
//First type relate with the argument send in execute()
//Second type relate with onProgressUpdate method which I haven't use in this code
//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// As you can see, doInBackground has taken an Array of Strings as the argument
//We need to specifically get the givenUsername and givenPassword
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("userID" + paramUsername + " password is :" + paramPassword);
// Create an intermediate to connect with the Internet
HttpClient httpClient = new DefaultHttpClient();
// Sending a GET request to the web page that we want
// Because of we are sending a GET request, we have to pass the values through the URL
HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/doLogin?userID=" + paramUsername + "&password=" + paramPassword);
try {
// execute(); executes a request using the default context.
// Then we assign the execution result to HttpResponse
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse// getEntity() ; obtains the message entity of this response");
// getContent() ; creates a new InputStream object of the entity.
// Now we need a readable source to read the byte stream that comes as the httpResponse
InputStream inputStream = httpResponse.getEntity().getContent();
// We have a byte stream. Next step is to convert it to a Character stream
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
//The buffer size is 8K
//Therefore we need a mechanism to append the separately coming chunks in to one String element
// We have to use a class that can handle modifiable sequence of characters for use in creating String
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
// There may be so many buffered chunks. We have to go through each and every chunk of characters
//and assign a each chunk to bufferedStrChunk String variable
//and append that value one by one to the stringBuilder
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
// Now we have the whole response as a String value.
//We return that value then the onPostExecute() can handle the content
System.out.println("Returninge of doInBackground :" + stringBuilder.toString());
// If the Username and Password match, it will return "working" as response
// If the Username or Password wrong, it will return "invalid" as response
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("Exceptionrates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
return null;
}
// Argument comes for this method according to the return type of the doInBackground() and
//it is the third generic type of the AsyncTask
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
if(result.equals("success"))
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
else {
Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
}
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(userID, password);
}
}
You can do like this.
In the onPostExecute() method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Post result :" + result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray login = jsonObject.getJSONArray("login");
JSONObject jsonObject1 = login.getJSONObject(0);
// edited second, you response was responsetype, but I parsed was responsetypes,so you can have a look.
String responsetypes = jsonObject1.optString("responsetypes");
// edited
String sessionid = jsonObject1.getString("sessionid");
if (TextUtils.equals(responsetypes, "success")) {
Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
} else if (TextUtils.equals(responsetypes, "failure")) {
// edited
String message = jsonObject1.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for example method get error response use volley.
private void getLogin() {
JSONObject param = new JSONObject();
try {
param.put("username", username.getText().toString());
param.put("password", password.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, param, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("login");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("sessionid>> ", jsonObject.getString("sessionid"));
}
dissmissPDialog();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error >> ", error.toString());
streror = error.toString();
dissmissPDialog();
}
}
);
normal.add(jsonObjectRequest);
}
Update your onPostExecute() method like this.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject1 = new JSONObject(result);
JSONArray jsonArray = jsonObject1.getJSONArray("login");
JSONObject jsonObjectLogin = jsonArray.getJSONObject(0);
String response = jsonObjectLogin.getString("responsetypes");
Toast.makeText(getApplicationContext(), +response, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
Let me know this is working or not.

JSON exception and permissions

I have written app for weather using open weather API.... but when i install the app in my phone and click on the button to determine weather it crashes... I use Android M in my phone
public class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
//combined the exceptions MalformedURL and IOException to a common to display a toast msg
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String msg = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for(int i = 0;i<arr.length();i++){
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String desc = "";
main = jsonPart.getString("main");
desc = jsonPart.getString("description");
icon = jsonPart.getString("icon");
if (main != "" && desc != "") {
msg += main + "\r\n" + desc;
}
}
if(msg != ""){
weatherReport.setText(msg);
}
else{
Toast.makeText(MainActivity.this,
"Location not able to determine",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(MainActivity.this,
"Location not able to determine",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
The error shown is that arr.length() is applied on a null array....
i don't get what the error is . is it about permissions ... if so how should i implement permissions in Marshmallow... this is the code that is inside onCreate(), if its about permissions pls tell how to implement..
try {
//to hide the keyboard after pressing the button
InputMethodManager manager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromInputMethod(weatherInput.getWindowToken(),0);
DownloadTask downloadTask = new DownloadTask();
//used to encode the entered input for url.. for example San Fransisco appears in url
//as San%20Fransisco ... and to enable that we use the encoder...
String encodedCity = URLEncoder.encode(city,"UTF-8");
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Logcat ..
02-25 22:56:54.009 1413-1413/com.example.hemantj.weather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hemantj.weather, PID: 1413
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:133)
at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
try {
Log.d(TAG, "onPostExecute: this inner of post" + getcontent_for_validate);
jsonobj = new JSONObject(getcontent_for_validate);
System.out.println("this is get content" + jsonobj.toString());
JSONArray array = jsonobj.getJSONArray("Staff_Details");
for (int i = 0; i < array.length(); i++) {
Clint_id = editText_user_name.getText().toString();
Api_key = array.getJSONObject(i).getString("api_key");
COMPANY_LOGO = array.getJSONObject(i).getString("company_logo");
Password = editText_password.getText().toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
internet permission only
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
error is in your onPostExecute()
new JSONArray(weatherInfo); //is returning null
so arr is null
what is value of weatherInfo?

How to retreive data from background thread to UI thread in aysnctask?

i have fetched data from my api but i don't know how to assign this fetched data to my adapter?
Issue:
how to set fetched data to array defined above?
how to set an adapter ?
public class FetchLists extends AsyncTask<>{
public List<MailChimpList> listTitles = new ArrayList<>();
#Override
protected List<MailChimpList> doInBackground(Integer... params) {
int count = params[0];
int offset = params[1];
String urlString = "https://us14.api.mailchimp.com/lists?apikey=efb918ee8791215bac4c8a3a8a77-us14"
urlString = urlString + "&count=" + count + "&offset=" + offset;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray lists = object.getJSONArray("lists");
for (int i = 0; i < lists.length(); i++) {
JSONObject listData = (JSONObject) lists.get(i);
MailChimpList mailChimpList = new MailChimpList();
mailChimpList.id = listData.getString("id");
mailChimpList.title = listData.getString("name");
String id = listData.getString("id");
String title = listData.getString("name");
Log.d("ashutosh","id are: "+id);
Log.d("ashutosh","list name are: "+title);
listTitles.add(mailChimpList);
}
} catch (Exception e) {
e.printStackTrace();
}
return listTitles;
}
#Override
protected void onPostExecute(List<MailChimpList> mailChimpLists) {
}
}
#Override
protected void onPostExecute(List<MailChimpList> mailChimpLists) {
MyCustomAdapter adapter = new MyCustomAdapter(context, mailChimpLists);
myListView.setAdapter(adapter);
}
As your list is customized list you need to write a customer adapter
You can declare your ListView as global variable and it can be accessed in post execute.

android:how to call method from hyperlink

I am trying to click a hyperlink and call method in android programming...
But the problem is , the link is not showing up and neither the method is getting called. How to achieve this result?
I am basically a javascript/jsp developer, this is my first android application , which i am learning. Accordingly i am trying to click link and call method with parameter....
Results looking like
Java code
private class CallAPI extends AsyncTask<String, String, String> {
private String Content;
#Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
emailVerificationResult result = null;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
System.out.println("test");
BufferedReader reader = null;
// Get the server response
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
/****************** Start Parse Response JSON Data *************/
String OutputData = "<center><b><u>Weight Training</u></b></center><br/><br/>";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("articleList");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for (int i = 0; i < lengthJsonArr; i++) {
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("menu_name").toString();
String number = jsonChildNode.optString("id").toString();
String date_added = jsonChildNode.optString("parent_id").toString();
OutputData += " " +
String.format("<a onClick='verifyEmail("+number+","+date_added+")'><b>"+name+"<b> "+ number+" "+ date_added+"</a> ") +"<br/><br/>";
}
/****************** End Parse Response JSON Data *************/
/* Show Parsed Output on screen (activity) */
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
resultToDisplay =OutputData ;
return resultToDisplay;
}
// This is the method that is called when the submit button is clicked
public void verifyEmail(String m,String p) {
String urlString = apiURL + "mid=" + m + "&pid=" + p;
new CallAPI().execute(urlString);
}
protected void onPostExecute(String result) {
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
Update:
Instead of link, can i put a button and provide on click method and pass parameter to the method
(Thankfully) You cannot call a function using HTML tags in android. Instead try setting ClickableSpan on you you TextView to get the desired effect
SpannableString ss = new SpannableString("Click Me to do magic");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
doSomeMagic();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
}
};
// apply the clickable span on "Click Me" part which is on index 0 -> 7
// 8 is used because it goes from a -> b-1
ss.setSpan(clickableSpan, 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textView = (TextView) findViewById(R.id.foo);
textView.setText(ss);

android HttpGet/HttpPost parameters allways arrive as null to the server

I'm trying to send data to the server but it seems that I always send null values, any idea? The idea is to add a new customer through the mobile application to my database hosted in a server.
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nuevo_insert);
//etResponse = (EditText) findViewById(R.id.etResponse2);
etNombre = (EditText) findViewById(R.id.etNombre);
etApellido = (EditText) findViewById(R.id.etApellido);
etEdad = (EditText) findViewById(R.id.etEdad);
nombre = etNombre.getText().toString();
apellido = etApellido.getText().toString();
edad = etEdad.getText().toString();
}
public void insertar(View view) {
// Call AsyncTask to perform network operation on separate thread
// working in localhost you CAN'T put localhost in that address, you
// MUST put your IP address or it will crush
new HttpAsyncTask().execute("http://192.168.1.34/android/insertCustomer.php");
}
public static String GET(String url) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
// receive response as InputStream
inputStream = httpResponse.getEntity().getContent();
// convert InputStream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else {
result = "No ha funcionat!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask
#Override
protected void onPostExecute(String result) {
String s = "";
Toast.makeText(getBaseContext(),getResources().getString(R.string.rebut), Toast.LENGTH_LONG).show();
JSONArray jArray;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "Nom: " + json.getString("FirsName") + " "
+ json.getString("LastName") + "\n" + "Edat: "+ json.getInt("Age") + "\n\n";
}
etResponse.setText(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my php file:
<?php
$con = mysql_connect('localhost', 'root', '');
if(!$con){
die("No se ha podido realizar la conexion: ".mysql_error());
}
mysql_select_db("TestDatabase", $con);
$nombre = $_GET['nombre'];
$apellido = $_GET['apellido'];
$edad = $_GET['edad'];
print_r($nombre."-".$apellido."-".$edad);
$result = mysql_query("insert into customer(FirsName, LastName, Age) values ('$nombre', '$apellido', '$edad')");
mysql_close($con);
?>
OK the problem was that I was retrieving the data from EditText boxes in the onCreate and I had to do it in the GET method :-)
If you are getting null value means that mean u r passing wrong type parameters or url may be wrong you do check it out
Change
HttpResponse httpResponse = httpClient.execute(new HttpGet(url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad));
to this:
String request = url+ "?nombre=" + nombre + "&apellido=" + apellido + "&edad="+ edad;
Log.d("DEBUG", request);
HttpResponse httpResponse = httpClient.execute(request);
and see your logcat for your url, maybe it is broken.
if the url is ok, then try opening this url in your browser and check the results.

Categories

Resources