Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello everyone I m sorry if this has been asked earlier , i have been searching for this solution since past 3 days.I am new in android and php.
I want to know how can i send "jsonArray"(shown below) to my php server and then extract jsonobject values recieved in php.
I have tried jsonarrayrequest and hashmap but was not able to send. Please help.
String url="http://192.168.43.210/jjj.php";
JSONArray list;
RequestQueue requestQueue;
final JSONArray jsonArray=new JSONArray();
for (int i=0;i<valu;i++)
{
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("comptext",smslist.get(i).completeText);
jsonObject.put("amount",smslist.get(i).amount);
jsonObject.put("txntype",smslist.get(i).txnType);
jsonObject.put("party",smslist.get(i).party);
jsonObject.put("from",smslist.get(i).fromNo);
jsonObject.put("datetime",smslist.get(i).dateTime);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
result.append("Successfully sent");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
protected Map<JSONArray,JSONArray> getparams() throws AuthFailureError{
Map<JSONArray,JSONArray> parameters = new HashMap<JSONArray, JSONArray>();
parameters.put(list,jsonArray);
return parameters;
}
};
requestQueue.add(jsonArrayRequest);
}
});
Use StringRequest instead of JsonArrayRequest for example:
private void register() {
if (!validate()) {
onRegistrationFailed("Registration Failed");
return;
}
final String name = et_username.getText().toString();
final String email = et_email.getText().toString();
final String phone = et_phone.getText().toString();
final String password = et_password.getText().toString();
showDialog();
StringRequest strRequest = new StringRequest(Request.Method.POST, Config.MAIN_URL + Config.REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String msg = jsonObject.getString("message");
if (status == SUCCESS) {
onRegistrationSuccess(name,email);
} else {
onRegistrationFailed(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
hideDialog();
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put(Config.KEY_USERNAME, name);
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PHONE, phone);
params.put(Config.KEY_PASSWORD, password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strRequest);
}
This is working code for login sample. so try this, and change as per your need.
Login.java
package com.example.volleytest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class Login extends AppCompatActivity{
public static final String LOGIN_URL = "YOUR_URL";
//"http://192.168.1.100/Login/admin.php";
ProgressDialog pDialog;
public static final String KEY_USERNAME="username";
public static final String KEY_PASSWORD="password";
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonLogin;
private String username;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isNetworkAvailable()){
userLogin();
}
else
{
showMessageDialog("Error", "Check your Internet Connection..!");
}
}
});
}
private void userLogin() {
username = editTextUsername.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//JSONArray myJSON= new JSONArray(response);
JSONObject parentObject = new JSONObject(response);
JSONObject childObject = parentObject.getJSONObject("Tracking");
String status = childObject.optString("status");
String type = childObject.optString("type");
//System.out.println("status : " + status);
//System.out.println("Type : " + type);
if(status.trim().equals("success"))
{
pDialog.hide();
showMessageDialog("Login", type + " Login Successfully..!");
}
else
{
pDialog.hide();
showMessageDialog("Login", "No Users/Admin were Found..! ");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
pDialog.hide();
showMessageDialog("JSON Error", "Server Error..! Try after Some Time..!");//e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
pDialog.hide();
//showMessageDialog("Login", "Reponse => " + error.toString());
showMessageDialog("Login", "Server Error..! Try after Some Time..!");
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put(KEY_USERNAME,username);
map.put(KEY_PASSWORD,password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showMessageDialog(String title , String Message)
{
AlertDialog dialog = new AlertDialog.Builder(Login.this)
.setTitle(title)
.setMessage(Message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.show();
//TextView textView = (TextView) dialog.findViewById(android.R.id.message);
//textView.setTextSize(25);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20dp"
android:text="Login Using Volley Library"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Enter Username"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextUsername" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Password"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:id="#+id/editTextPassword" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/buttonLogin" />
</LinearLayout>
Related
I'm making a simple program where I can get a content from JSON in this url
https://www.haliminfo.com/feeds/posts/summary/?max-results=10&start-index=1&alt=json
and make it a list Using RecyclerView on Android.
I have made several necessary components such as Model, Adapter, Post Row Item and HttpHandler
when I try RecyclerView with a method like this it works.
private void addData () {
postsArrayList = new ArrayList <> ();
postsArrayList.add (new Posts ("TITLE", "SUMMARY"));
}
but when I apply the method below nothing appears in the activity
private class getContent extends AsyncTask <Void, Void, Void> {
# Override
protected Void doInBackground (Void ... voids) {
HttpHandler sh = new HttpHandler ();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall (URL_FIX);
if (jsonStr! = null) {
try {
JSONObject jsonObj = new JSONObject (jsonStr);
JSONObject feed = jsonObj.getJSONObject ("feed");
JSONArray entry = feed.getJSONArray ("entry");
Posts postsModel = new Posts ();
for (int i = 0; i <entry.length (); i ++) {
postsModel.setTitle (entry.getJSONObject (i) .getJSONObject ("title"). getString ("$ t"));
postsModel.setSummary (entry.getJSONObject (i) .getJSONObject ("summary"). getString ("$ t"));
postsArrayList.add (postsModel);
}
} catch (final JSONException e) {
Log.e ("RESPONSE", "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 ("RESPONSE", "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;
}
}
this is a full file of some important files in my project
MainActivity.java
package com.badjing.bloggercoba.activities;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.badjing.bloggercoba.R;
import com.badjing.bloggercoba.adapter.PostRecyclerViewAdapter;
import com.badjing.bloggercoba.config.Config;
import com.badjing.bloggercoba.handler.HttpHandler;
import com.badjing.bloggercoba.model.Posts;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private PostRecyclerViewAdapter postAdapter;
private ArrayList<Posts> postsArrayList;
private ProgressDialog pDialog;
private Config config = new Config();
String URL_FIX = Config.BLOG_URL + Config.BLOG_URL_MAX_RESULT + Config.MAX_RESULT + config.BLOG_URL_START_INDEX + config.START_INDEX + config.BLOG_URL_ALT_TYPE;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postsArrayList = new ArrayList<>();
new getContent().execute();
recyclerView = (RecyclerView) findViewById(R.id.post_recycle_view);
postAdapter = new PostRecyclerViewAdapter(postsArrayList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(postAdapter);
}
// private void addData() {
//
// postsArrayList = new ArrayList<>();
// postsArrayList.add(new Posts("JUDUL", "SUMMARY"));
//
// }
private class getContent 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... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL_FIX);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject feed = jsonObj.getJSONObject("feed");
JSONArray entry = feed.getJSONArray("entry");
Posts postsModel = new Posts();
for (int i = 0; i < entry.length(); i++) {
postsModel.setTitle(entry.getJSONObject(i).getJSONObject("title").getString("$t"));
postsModel.setSummary(entry.getJSONObject(i).getJSONObject("summary").getString("$t"));
postsArrayList.add(postsModel);
}
} catch (final JSONException e) {
Log.e("RESPONSE", "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("RESPONSE", "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;
}
}
private void urlBuilder() {
URL_FIX = Config.BLOG_URL + Config.BLOG_URL_MAX_RESULT + 10 + config.BLOG_URL_START_INDEX + 1 + config.BLOG_URL_ALT_TYPE;
}
}
Post.java (post model)
package com.badjing.bloggercoba.model;
public class Posts {
String title;
String summary;
public Posts() {
}
public Posts(String title, String summary) {
this.title = title;
this.summary = summary;
}
public String getTitle() {
return title;
}
public String getSummary() {
return summary;
}
public void setTitle(String title) {
this.title = title;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
PostRecyclerViewAdapter.java
package com.badjing.bloggercoba.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.badjing.bloggercoba.R;
import com.badjing.bloggercoba.model.Posts;
import java.util.ArrayList;
public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostRecyclerViewAdapter.MyViewHolder> {
private ArrayList<Posts> postsList;
public PostRecyclerViewAdapter(ArrayList<Posts> postsArrayList) {
this.postsList = postsArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.post_row_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.blog_post_title.setText(postsList.get(position).getTitle());
holder.blog_post_sumary.setText(postsList.get(position).getSummary());
}
#Override
public int getItemCount() {
return (postsList!= null) ? postsList.size() : 0;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView blog_post_title, blog_post_sumary, blog_post_author;
ImageView img_thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
blog_post_title = itemView.findViewById(R.id.blog_post_title);
blog_post_sumary = itemView.findViewById(R.id.blog_post_sumary);
// blog_post_author = itemView.findViewById(R.id.blog_post_author);
// img_thumbnail = itemView.findViewById(R.id.post_thumbnail);
}
}
}
post_row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="5dp"
android:padding="8dp"
android:background="#fff">
<ImageView
android:id="#+id/post_thumbnail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/loading_shape"></ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="230dp"
android:orientation="vertical"
android:layout_margin="8dp" >
<TextView
android:id="#+id/blog_post_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blog post title"
android:textSize="20dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/blog_post_sumary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blog post summary"/>
<TextView
android:id="#+id/blog_post_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="~ author"/>
</LinearLayout>
</LinearLayout>
thank you for your attention and help.
I have and xml activity, it contains a spinner item, I want to pass the value of spinner to other textView on the same activity. Attached tow files xml and java, and the spinner name is simpleSpinner and the textView that I want to have the spinner value is district_id please update the code and help me
package com.cp.comp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class add_comp extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"جنين","2","طولكرم","نابلس","قلقيلية","سلفيت","رام الله","اريحا","بيت لحم","القدس","الخليل"};
private EditText shop_name, complainant_name, complainant_id, mobile;
private EditText district_id, address_detail, comp_type, comp_detail;
private ProgressBar loading;
private static String URL_ADDCOMP = "http://172.23.50.55/CP/add_comp.php";
private Button btn_add_comp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_comp);
btn_add_comp = findViewById(R.id.btn_add_comp);
loading = findViewById(R.id.loading);
shop_name = findViewById(R.id.shop_name);
complainant_name = findViewById(R.id.complainant_name);
complainant_id = findViewById(R.id.complainant_id);
mobile = findViewById(R.id.mobile);
district_id = findViewById(R.id.district_id);
address_detail = findViewById(R.id.address_detail);
comp_type = findViewById(R.id.comp_type);
comp_detail = findViewById(R.id.comp_detail);
Spinner spin = (Spinner) findViewById(R.id.district_id);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
btn_add_comp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_comp();
}
});
private void Add_comp() {
loading.setVisibility(View.VISIBLE);
btn_add_comp.setVisibility(View.GONE);
final String shop_name = this.shop_name.getText().toString().trim();
final String complainant_name = this.complainant_name.getText().toString().trim();
final String complainant_id = this.complainant_id.getText().toString().trim();
final String mobile = this.mobile.getText().toString().trim();
final String district_id = this.district_id.getText().toString().trim();
final String address_detail = this.address_detail.getText().toString().trim();
final String comp_type = this.comp_type.getText().toString().trim();
final String comp_detail = this.comp_detail.getText().toString().trim();
System.out.println("ya abed almoty " + comp_detail);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ADDCOMP,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
System.out.println("ya habibi");
if (success.equals("1")) {
Toast.makeText(add_comp.this, "تم إرسال الشكوى بنجاح!", Toast.LENGTH_SHORT).show();
System.out.println("ya belal");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(add_comp.this, "ارسال خاطئ! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_add_comp.setVisibility(View.VISIBLE);
System.out.println("ya jehad");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(add_comp.this, "ارسال خاطئ! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_add_comp.setVisibility(View.VISIBLE);
System.out.println("ya morad");
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("shop_name", shop_name);
params.put("complainant_name", complainant_name);
params.put("complainant_id", complainant_id);
params.put("mobile", mobile);
params.put("district_id", district_id);
params.put("address_detail", address_detail);
params.put("comp_type", comp_type);
params.put("comp_detail", comp_detail);
System.out.println("ya fahed" + params.put("comp_type", comp_type));
System.out.println("ya vvvvvvvvv" + bankNames.toString().trim());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
String district_id = bankNames[position];
System.out.println("bobobo " + district_id);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}}
and the xml file is :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="30dp"
android:paddingTop="80dp"
android:paddingRight="30dp"
tools:context="com.cp.comp.add_comp">
<EditText
android:id="#+id/shop_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="اسم المحل"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<EditText
android:id="#+id/complainant_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="اسم المشتكي"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<EditText
android:id="#+id/complainant_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="هوية المشتكي"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<EditText
android:id="#+id/mobile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="موبايل المشتكي"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<EditText
android:id="#+id/address_detail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="عنوان المحل التفصيلي"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<EditText
android:id="#+id/comp_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="طبيعة الشكوى"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<EditText
android:id="#+id/comp_detail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="تفصيل الشكوى"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<ProgressBar
android:id="#+id/loading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:visibility="gone" />
<EditText
android:id="#+id/district_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="المحافظة"
android:inputType="textPersonName"
android:textColor="#color/colorText" />
<Spinner
android:id="#+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<Button
android:id="#+id/btn_add_comp"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginTop="30dp"
android:backgroundTint="#color/colorPrimaryDark2"
android:text="ارسال"
android:textColor="#android:color/white" />
</LinearLayout>
To change a TextViews text you need to simply do it:
myTextView.setText(district_id);
package com.cp.comp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class add_comp extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private EditText shop_name, complainant_name, complainant_id, mobile;
private EditText district_id, address_detail, comp_type, comp_detail;
private EditText myTextView;
private ProgressBar loading;
private static String URL_ADDCOMP = "http://172.23.50.55/CP/add_comp.php";
private Button btn_add_comp;
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_comp);
sp=(Spinner)findViewById(R.id.spinner);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
System.out.println("frfrfrfr " + adapter);
sp.setAdapter(adapter);
btn_add_comp = findViewById(R.id.btn_add_comp);
loading = findViewById(R.id.loading);
shop_name = findViewById(R.id.shop_name);
complainant_name = findViewById(R.id.complainant_name);
complainant_id = findViewById(R.id.complainant_id);
mobile = findViewById(R.id.mobile);
district_id = findViewById(R.id.district_id);
address_detail = findViewById(R.id.address_detail);
comp_type = findViewById(R.id.comp_type);
comp_detail = findViewById(R.id.comp_detail);
btn_add_comp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_comp();
}
});
}
private void Add_comp() {
loading.setVisibility(View.VISIBLE);
btn_add_comp.setVisibility(View.GONE);
final String shop_name = this.shop_name.getText().toString().trim();
final String complainant_name = this.complainant_name.getText().toString().trim();
final String complainant_id = this.complainant_id.getText().toString().trim();
final String mobile = this.mobile.getText().toString().trim();
final String district_id = this.district_id.getText().toString().trim();
final String address_detail = this.address_detail.getText().toString().trim();
final String comp_type = this.comp_type.getText().toString().trim();
final String comp_detail = this.comp_detail.getText().toString().trim();
System.out.println("ya abed almoty");
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ADDCOMP,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
System.out.println("ya habibi");
if (success.equals("1")) {
Toast.makeText(add_comp.this, "تم إرسال الشكوى بنجاح!", Toast.LENGTH_SHORT).show();
System.out.println("ya belal");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(add_comp.this, "ارسال خاطئ! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_add_comp.setVisibility(View.VISIBLE);
System.out.println("ya jehad");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(add_comp.this, "ارسال خاطئ! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_add_comp.setVisibility(View.VISIBLE);
System.out.println("ya morad");
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("shop_name", shop_name);
params.put("complainant_name", complainant_name);
params.put("complainant_id", complainant_id);
params.put("mobile", mobile);
params.put("district_id", district_id);
params.put("address_detail", address_detail);
params.put("comp_type", comp_type);
params.put("comp_detail", comp_detail);
System.out.println("ya fahed" + params.put("comp_type", comp_type));
System.out.println("ya mymymymym" + myTextView);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onStart(){
super.onStart();
add_comp.BackTask bt=new add_comp.BackTask();
bt.execute();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
parent.getItemAtPosition(position).toString();
System.out.println("mrmrmr " + parent.getItemAtPosition(position).toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://172.23.50.55/CP/select_district_name.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("dis_name"));
System.out.println("txt_txt" + result);
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}
}
the dis_name is the value that I want to pass to district_id
package com.cp.comp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class add_comp extends AppCompatActivity {
private EditText shop_name, complainant_name, complainant_id, mobile;
private EditText district_id, address_detail, comp_type, comp_detail;
private ProgressBar loading;
private static String URL_ADDCOMP = "http://172.23.50.55/CP/add_comp.php";
private Button btn_add_comp;
ArrayList<String> listItems=new ArrayList<>();
ArrayAdapter<String> adapter;
Spinner sp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_comp);
btn_add_comp = findViewById(R.id.btn_add_comp);
loading = findViewById(R.id.loading);
shop_name = findViewById(R.id.shop_name);
complainant_name = findViewById(R.id.complainant_name);
complainant_id = findViewById(R.id.complainant_id);
mobile = findViewById(R.id.mobile);
district_id = findViewById(R.id.district_id);
address_detail = findViewById(R.id.address_detail);
comp_type = findViewById(R.id.comp_type);
comp_detail = findViewById(R.id.comp_detail);
sp=(Spinner)findViewById(R.id.spinner);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
sp.setAdapter(adapter);
btn_add_comp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_comp();
}
});
}
private void Add_comp() {
loading.setVisibility(View.VISIBLE);
btn_add_comp.setVisibility(View.GONE);
final String shop_name = this.shop_name.getText().toString().trim();
final String complainant_name = this.complainant_name.getText().toString().trim();
final String complainant_id = this.complainant_id.getText().toString().trim();
final String mobile = this.mobile.getText().toString().trim();
final String district_id = this.district_id.getText().toString().trim();
final String address_detail = this.address_detail.getText().toString().trim();
final String comp_type = this.comp_type.getText().toString().trim();
final String comp_detail = this.comp_detail.getText().toString().trim();
System.out.println("ya abed almoty");
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ADDCOMP,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
System.out.println("ya habibi");
if (success.equals("1")) {
Toast.makeText(add_comp.this, "تم إرسال الشكوى بنجاح!", Toast.LENGTH_SHORT).show();
System.out.println("ya belal");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(add_comp.this, "ارسال خاطئ! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_add_comp.setVisibility(View.VISIBLE);
System.out.println("ya jehad");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(add_comp.this, "ارسال خاطئ! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_add_comp.setVisibility(View.VISIBLE);
System.out.println("ya morad");
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("shop_name", shop_name);
params.put("complainant_name", complainant_name);
params.put("complainant_id", complainant_id);
params.put("mobile", mobile);
params.put("district_id", district_id);
params.put("address_detail", address_detail);
params.put("comp_type", comp_type);
params.put("comp_detail", comp_detail);
System.out.println("ya fahed" + params.put("comp_type", comp_type));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onStart(){
super.onStart();
add_comp.BackTask bt=new add_comp.BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://172.23.50.55/CP/select_district_name.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("dis_name"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}
}
the dis_name is the value that I want to pass to district_id
I want to trigger a button as soon as an OTP arrives and gets set in a edittext area field. OTP gets successfully set but submit button is not getting triggered itself. Where i am going wrong? Here is my code.
OTP.java
package com.nrb.app.nrb.otp;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.nrb.app.nrb.HomeScreen;
import com.nrb.app.nrb.QRresponse.MyDBHelper;
import com.nrb.app.nrb.QRresponse.ServiceCalls;
import com.nrb.app.nrb.QRscanapi.RM;
import com.nrb.app.nrb.R;
import com.nrb.app.nrb.intera.AsyncResponseActivity;
import com.nrb.app.nrb.intera.ConnectionDetectorActivity;
import com.nrb.app.nrb.login.RegisterValidation;
import com.nrb.app.nrb.login.SignInActivity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class OTP extends FragmentActivity implements View.OnClickListener {
private Hashtable<String, String> verifiedResponseKeyValue = new Hashtable<String, String>();
private Hashtable<String, String> verifiedNestedResponseKeyValue = new Hashtable<String, String>();
private String userMobValue;
private String otpVerUrl;
private String userNameValue;
private String userEmailValue;
private String userCountryValue;
private String userId;
private MyDBHelper myDBHelper;
private String userCountryCode;
private boolean timeOut;
static EditText OtpNumber;
private ConnectionDetectorActivity cd;
private String user_exist;
private Button OTP;
Context cntx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cntx=this;
OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
cd = new ConnectionDetectorActivity(OTP.this);
Bundle bundle = getIntent().getExtras();
userId=bundle.getString("id");
userEmailValue = bundle.getString("userEmailValue");
userMobValue = bundle.getString("userMobValue");
userNameValue = bundle.getString("userNameValue");
userCountryValue = bundle.getString("userCountryValue");
userCountryCode = bundle.getString("userCountryCode");
user_exist = bundle.getString("user_exist");
registerViews();
}
public void registerViews() {
OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
// TextWatcher would let us check validation error on the fly
OtpNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
RegisterValidation.isName(OtpNumber, false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
/* OtpNumber.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
OTP.performClick();
return true;
}
return false;
}
});*/
}
private boolean checkValidation() {
boolean ret = true;
if (!RegisterValidation.isName(OtpNumber, true))
ret = false;
return ret;
}
#SuppressLint("InflateParams")
private void popUpDialog(String result1, final boolean newuser) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.otp_verification_dialog, null);
TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
tv.setText(result1);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
if (newuser) {
Bundle bundle = new Bundle();
bundle.putString("defaultFrag", "newUserFrag");
Intent i = new Intent(OTP.this, HomeScreen.class);
i.putExtras(bundle);
startActivity(i);
setResult(10);
finish();
}
else{
Toast.makeText(cntx, "Please enter Valid OTP", Toast.LENGTH_LONG).show();
OtpNumber.setText("");
}
}
});
}
#SuppressLint("InflateParams")
private void popUpDialogSuccess(Spannable result1) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.otp_verification_dialog, null);
TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
tv.setText(result1);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
insertUserPfref();
}
});
}
public void verifyOTPKEY(View v) {
if (checkValidation()){
EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
RM.OTP_MOB_VALUE = userMobValue;
if (user_exist.compareTo("true") == 0)
RM.OTP_USER_EXIST_VALUE = "true";
else
RM.OTP_USER_EXIST_VALUE = "false";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
jsonObject.put(RM.USER_Id_KEY,userId);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("==", "========= FAIL TO CREATE JSON ==========");
}
ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {
#Override
public void myAsyncResponse(String result) {
// TODO Auto-generated method stub
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
Log.d("====>>>>", result);
parseOTPRsponseJason(result);
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
}
});
if (cd.isConnectingToInternet()) {
Login.execute(1);
} else {
showNetworFailDialog(RM.NO_INTERNET_MSG);
}
}
else{
Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
}
class MyOTPAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(OTP.this);
dialog.setMessage("Authenticating...");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(otpVerUrl);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} catch (Exception e) {
timeOut = true;
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// popUpDialog(result);
if (!timeOut)
parseOTPRsponseJason(result);
else
showNetworFailDialog(RM.REQ_TIMEOUT_MSG);
Log.d("----->", " Response " + result);
}
}
private void parseOTPRsponseJason(String result) {
// TODO Auto-generated method stub
JSONObject json;
JSONObject nestedJson;
try {
json = new JSONObject(result);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = json.get(key);
if (user_exist.compareTo("true") == 0) {
if (key.compareTo("responseHash") == 0) {
nestedJson = new JSONObject(json.get(key).toString());
Iterator<String> nestedIter = nestedJson.keys();
while (nestedIter.hasNext()) {
String nestedKey = nestedIter.next();
Object nestedValue = nestedJson.get(nestedKey);
verifiedNestedResponseKeyValue.put(nestedKey,
nestedValue.toString());
}
}
}
verifiedResponseKeyValue.put(key, value.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Set<String> hKeys2 = verifiedResponseKeyValue.keySet();
for (String string : hKeys2) {
Log.d("====>",
string + " ==>" + verifiedResponseKeyValue.get(string));
}
String x = verifiedResponseKeyValue.get("success");
if (x.compareTo("true") == 0) {
if (user_exist.compareTo("true") == 0) {
userNameValue = verifiedNestedResponseKeyValue.get("name");
Spannable wordtoSpan = new SpannableString("HI "
+ userNameValue + " , Welcome back to Onspot");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 3,
3 + userNameValue.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
popUpDialogSuccess(wordtoSpan);
} else {
Spannable wordtoSpan = new SpannableString(
"Congratulations! " + userNameValue
+ " , you are successfully registered.");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 17,
17 + userNameValue.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
popUpDialogSuccess(wordtoSpan);
}
} else
popUpDialog(
verifiedResponseKeyValue.get("responseMessage"), false);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("====>", "Exception");
popUpDialog(RM.CrashError, false);
}
}
private void insertUserPfref() {
// TODO Auto-generated method stub
myDBHelper = new MyDBHelper(OTP.this);
myDBHelper.getWritableDatabase();
if (user_exist.compareTo("true") == 0) {
try {
myDBHelper.insertRegisteredUser(
verifiedNestedResponseKeyValue.get("email"), //
verifiedNestedResponseKeyValue.get("mobile_number"),//
verifiedNestedResponseKeyValue.get("name"), //
verifiedNestedResponseKeyValue.get("country"),
//
verifiedNestedResponseKeyValue.get("country_code"));
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("====>", "Exception");
popUpDialog(RM.CrashError, false);
}
Log.d("------>", "Existing USER");
Log.d("------>", "Existing USER" + user_exist);
} else {
myDBHelper.insertRegisteredUser(userEmailValue,//
userMobValue,//
userNameValue, //
userCountryValue,//
userCountryCode);
Log.d("------>", "New User");
Log.d("------>", "New User" + user_exist);
}
Log.d("------>", user_exist);
startActivity(new Intent(OTP.this, HomeScreen.class));
setResult(10);
finish();
}
#SuppressLint("InflateParams")
private void showNetworFailDialog(String msg) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.network_failure_dialog, null);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
TextView tvMsg = (TextView) content.findViewById(R.id.networkFailMsg);
tvMsg.setText(msg);
content.findViewById(R.id.btnNetworkFailureOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
setResult(10);
finish();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(OTP.this, SignInActivity.class);
startActivity(i);
setResult(10);
finish();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
public void recivedSms(String message)
{
try
{
int pos=message.indexOf(':');
String msg = message.substring(pos + 2);
OtpNumber.setText(msg);
OTP = (Button) findViewById(R.id.btnOTPVerify);
OTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
OTP.performClick();
OTP.setPressed(true);
/* if(OtpNumber!=null) {
if (checkValidation()) {
EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
RM.OTP_MOB_VALUE = userMobValue;
if (user_exist.compareTo("true") == 0)
RM.OTP_USER_EXIST_VALUE = "true";
else
RM.OTP_USER_EXIST_VALUE = "false";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
jsonObject.put(RM.USER_Id_KEY, userId);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("==", "========= FAIL TO CREATE JSON ==========");
}
ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {
#Override
public void myAsyncResponse(String result) {
// TODO Auto-generated method stub
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
Log.d("====>>>>", result);
parseOTPRsponseJason(result);
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
}
});
if (cd.isConnectingToInternet()) {
Login.execute(1);
} else {
showNetworFailDialog(RM.NO_INTERNET_MSG);
}
} else {
Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
}
}*/
}
catch (Exception e)
{
}
}
}
IncomingMsg.java
package com.nrb.app.nrb.otp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
/**
* Created by Neha on 07-03-2016.
*/
public class IncomingMsg extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
final Bundle bundle = intent.getExtras();
try {
if (bundle != null)
{
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++)
{
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber ;
String message = currentMessage.getDisplayMessageBody();
try
{
if (senderNum.equals("DZ-Onspot"))
{
OTP Sms = new OTP();
Sms.recivedSms(message );
}
}
catch(Exception e){}
}
}
} catch (Exception e)
{
}
}
}
activity_otp.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ripple="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="25dp"
android:gravity="center"
android:orientation="vertical"
android:background="#fff"
android:padding="10dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/onspot" />
<EditText
android:id="#+id/etOTPVerifaction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:inputType="textCapCharacters"
android:ems="10"
android:hint="Enter Verification Key"
android:maxLength="10"
android:singleLine="true">
</EditText>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:padding="5dp"
android:onClick="verifyOTPKEY">
<com.andexert.library.RippleView
android:id="#+id/ripple1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:rv_rippleDuration="200"
app:rv_type="rectangle" >
<Button
android:id="#+id/btnOTPVerify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button_shadow"
android:text="SUBMIT"
android:onClick="verifyOTPKEY"
android:textColor="#color/white" />
</com.andexert.library.RippleView>
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="verifyOTP"
android:text="Enter Verification key For Login"
android:textAppearance="?android:attr/textAppearanceSmall" />
You're setting it to do nothing. You should comment out these line
OTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
Have you tried putting performClick inside Runnable like this,
OTP.post(new Runnable(){
#Override
public void run() {
OTP.performClick();
}
});
OR
Use view tree observer which is used to register listeners that can be notified of global changes in the view tree like here which is efficient in higher level of api than 16
ViewTreeObserver vt = OTP.getViewTreeObserver();
vt.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
vt.removeOnGlobalLayoutListener(this);
OTP.performClick();
}
});
This is my activity where I display my data from an online database. What I'm trying to do is - when clicking an item inside the listview it can delete an item. But it is not working, can you help me?.
Here is my code:
ListOfOrders.java
package com.system.receivingoforder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.system.receivingoforder.app.AppConfig;
import com.system.receivingoforder.app.AppController;
public class ListOfOrders extends ListActivity{
private static final String TAG = RegisterActivity.class.getSimpleName();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
Typeface customFont;
TextView list_of_orders_txt;
ListView listView1;
SimpleAdapter adapter;
String[] table = new String[9999];
String desc[] = new String[9999];
String price[] = new String[9999];
String quantity[] = new String[9999];
String num, info;
int x;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listoforders);
customFont = Typeface.createFromAsset(getAssets(), "fonts/EraserRegular.ttf");
list_of_orders_txt = (TextView)findViewById(R.id.list_of_orders_tv);
list_of_orders_txt.setTypeface(customFont);
adapter = new SimpleAdapter( this, list, R.layout.listoforders_items,
new String[] {"title","subtitle"},
new int[] {R.id.loo_tablenumber,R.id.loo_itemquantity} );
getOrderDetails();
}
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
deleteOrder(table[position], desc[position], price[position], quantity[position]);
}
public void getOrderDetails() {
// Tag used to cancel the request
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONObject user = jObj.getJSONObject("user");
JSONArray tablenumarray = jObj.getJSONArray("tablearray");
JSONArray descarray = jObj.getJSONArray("descarray");
JSONArray pricearray = jObj.getJSONArray("pricearray");
JSONArray quantityarray = jObj.getJSONArray("quantityarray");
num = user.getString("prows");
x = Integer.parseInt(num);
HashMap<String,String> map = new HashMap<String,String>();
for(int i=0; i<x; i++) {
table[i] = tablenumarray.getString(i);
//treatment[i] = treatmentarray.getString(i);
desc[i] = descarray.getString(i);
price[i] = pricearray.getString(i);
quantity[i] = quantityarray.getString(i);
}
for(int i=0; i<x; i++) {
info = "Description: " + desc[i].toString() + " \n" + "Price: " + price[i].toString() + " \n" + "Quantity: " + quantity[i].toString();
map = new HashMap<String,String>();
map.put("title", "Table Number: " + table[i].toString());
map.put("subtitle", info);
list.add(map);
}
setListAdapter(adapter);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "orderinfo");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
//delete Order
private void deleteOrder(final String tablenum, final String desc, final String price, final String quantity) {
// Tag used to cancel the request
String tag_string_req = "req_registerpatient";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
Toast.makeText(getApplicationContext(), "Order Deleted", Toast.LENGTH_LONG).show();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "deleteorder");
params.put("tablenum", tablenum);
params.put("desc", desc);
params.put("price", price);
params.put("quantity", quantity);
//params.remove("tablenum");
//params.remove("desc");
//params.remove("price");
//params.remove("quantity");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
RegisterActivity.java
package com.system.receivingoforder;
import com.system.receivingoforder.app.AppConfig;
import com.system.receivingoforder.app.AppController;
import com.system.receivingoforder.helper.SQLiteHandler;
import com.system.receivingoforder.helper.SessionManager;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
listoforders.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/greenboard_background" >
<TextView
android:id="#+id/list_of_orders_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="#string/list_of_orders"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="35sp" />
<ListView
android:id="#+id/android:list"
android:layout_width="543dp"
android:layout_height="800dp"
android:layout_below="#+id/list_of_orders_tv"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
listoforders_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/loo_tablenumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/table_no"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp" />
<TextView
android:id="#+id/loo_itemquantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/loo_tablenumber"
android:text="#string/item_quantity"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp" />
</RelativeLayout>
You use arraylist so you can use arrayList.remove(position) and after that you just need to add adapter.notifyDataSetChanged();
i get error An exception occurred: android.os.NetworkOnMainThreadException even when i already use AsyncTask. Error is on LongOperation.java at the line
while ((line = reader.readLine()) != null) {
here is the code:
AsyncTaskActivity.java:
package com.example.myfirstapp;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
try {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(new LongOperation().execute("http://search.twitter.com/search.json?q=javacodegeeks").get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="10dip" >
</ProgressBar>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Progress" >
</Button>
<TextView
android:id="#+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replace" />
</LinearLayout>
LongOperation.java:
package com.example.myfirstapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.os.AsyncTask;
import android.util.Log;
public class LongOperation extends AsyncTask<String, Void, String> {
InputStream is = null;
#Override
protected String doInBackground(String... urls) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
return is.toString();
}
#Override
protected void onPostExecute(String result) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
// System.out.println("Result = " + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
is there anyone can help?
onPostExecute() and onPreExecute() run on the main UI thread. Move network operations to doInBackground().
new LongOperation().execute("http://search.twitter.com/search.json?q=javacodegeeks").get()
Calling get() does not make it asynchronous anymore. Blocks the ui thread.
public final Result get ()
Waits if necessary for the computation to complete, and then retrieves its result.
You need
new LongOperation().execute("http://search.twitter.com/search.json?q=javacodegeeks")
I would use a interface as a callback to communicate the result back to the activity.
Something like the answer by blackbelt in the below link
How do I return a boolean from AsyncTask?
Also move all your network related operation to doInbackground and update ui in onPostExecute
Example:
public class MainActivity extends Activity implements LongOperation.callBack {
Button btn;
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.textView1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LongOperation(MainActivity.this).execute("http://search.twitter.com/search.json?q=javacodegeeks");
}
});
}
#Override
public void returnText(String value) {
// TODO Auto-generated method stub
txt.setText(value);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="TextView" />
</RelativeLayout>
LongOperation.java
public class LongOperation extends AsyncTask<String, Void, String> {
InputStream is = null;
String _response;
callBack cb;
ProgressDialog pd;
interface callBack
{
public void returnText(String value);
};
public LongOperation(Context context) {
// TODO Auto-generated constructor stub
cb = (callBack) context;
pd = new ProgressDialog(context);
pd.setMessage("LongOperation...");
}
#Override
protected String doInBackground(String... urls) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.dismiss();
if(cb!=null)
{
cb.returnText(result);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}