Passing spinner data to other field - java

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

Related

I am making activity that translate 1 language to another(eng-french).Everything is working fine except i have to click button many times to work

In my activity, I want to take voice input when we click imageView and convert into text and display it in textfield and after we press button it converts it into french(currently it is fixed) and display it in textfield2.
I am using yandex translator.
My error::
When I click button for the first time nothing happens in textfield2 but in log, it display the correct translation.After my 2nd click,it changes the textfield2. But i want to show the translation after 1st click only.Why it is taking 2 click for working while my output is coming correct after 2nd click??
here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_centerHorizontal="true"
android:layout_below="#+id/textView"
tools:layout_editor_absoluteX="131dp"
tools:layout_editor_absoluteY="202dp" />
<ImageView
android:id="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_width="267dp"
android:layout_height="244dp"
app:srcCompat="#android:drawable/ic_btn_speak_now" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:text="Text to be Translated" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button"
android:text="Translated Text"
android:textSize="30sp"
/>
</RelativeLayout>
Here is my MainActivty:
package com.example.translator;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
final static int REQUEST_CODE_SPEECH=1000;
ImageView listen;
TextView ans,mresult;
Context context=this;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listen=findViewById(R.id.imageView);
ans=findViewById(R.id.textView);
mresult=findViewById(R.id.textView2);
b=findViewById(R.id.button);
listen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textToBeTranslated = ans.getText().toString();
String languagePair = "en-fr"; //English to French ("<source_language>-<target_language>")
//Executing the translation function
Translate(textToBeTranslated,languagePair);
}
});
}
void Translate(String textToBeTranslated,String languagePair){
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB) {
translatorBackgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,textToBeTranslated,languagePair);
} else {
translatorBackgroundTask.execute(textToBeTranslated,languagePair);
}
Log.d("Translation Result:", translatorBackgroundTask.t); // Logs the result in Android Monitor
mresult.setText(translatorBackgroundTask.t);
}
void speak(){
Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "hi say something!!!");
try{
startActivityForResult(intent,REQUEST_CODE_SPEECH);
}
catch(Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case REQUEST_CODE_SPEECH:{
if(resultCode==RESULT_OK && data!=null) {
ArrayList<String>result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ans.setText(result.get(0));
}
break;
}
}
}
}
Here is my API File:
package com.example.translator;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
//Declare Context
Context ctx;
public static String t="";
//Set Context
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
#Override
public String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey = "MY-API-KEY";
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
String resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
t=resultString;
return jsonStringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I think it's this line:
mresult.setText(TranslatorBackgroundTask.t);
Shouldn't it be:
mresult.setText(translatorBackgroundTask.t);

Controlling an AsynTaskLoader using a button click

I have created an app that displays a list of 10 books based on a query keyword entered by the user.
I have used an EditText View for the user to enter the query.
I have also used an ImageButton for the search button.
I have used a custom class that extents AsyncTaskLoader to load content to my ListView.
I have called the initloader() method from the MainActivity of the app and has called my custom loader from the OnCreateLoader override method.
I want the loader to fetch the data only on a button click and not automatically when the activity starts.
Main Activity
package com.example.shara.booklistapp;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.app.LoaderManager.*;
import static com.example.shara.booklistapp.BookQueryUtils.LOG_TAG;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Blist>> {
private ListAdapter mAdapter;
private static final int BOOK_LOADER_ID = 1;
private String Book_list_request_url = "Michael Jackson";
private ProgressBar progressBar;
private NetworkInfo networkInfo;
private TextView emptytextview;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView booklistview = findViewById(R.id.list);
progressBar = findViewById(R.id.progressbar);
mAdapter = new ListAdapter(this, new ArrayList<Blist>());
booklistview.setAdapter(mAdapter);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connectivityManager.getActiveNetworkInfo();
emptytextview = (TextView) findViewById(R.id.emptytextview);
editText = findViewById(R.id.search_query_text_view);
booklistview.setEmptyView(emptytextview);
booklistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Blist currentBook = mAdapter.getItem(position);
Uri currentbookk = Uri.parse(currentBook.getUrl());
startActivity(new Intent(Intent.ACTION_VIEW, currentbookk));
}
});
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
}
//Overriding the abstract methods of the Loadermanager
#Override
public Loader<List<Blist>> onCreateLoader(int id, Bundle bundle) {
Log.i(LOG_TAG, Book_list_request_url);
return new BlistLoader(this, Book_list_request_url);
}
#Override
public void onLoadFinished(Loader<List<Blist>> loader, List<Blist> blists) {
progressBar.setVisibility(View.GONE);
//Using the networkInfo variable declared earlier to check whether the system has internet connectivity and displays a message if there isn't one.
if (networkInfo == null) {
emptytextview.setText(R.string.no_network);
} else {
emptytextview.setVisibility(View.GONE);
}
mAdapter.clear();
if (blists != null && !blists.isEmpty()) {
mAdapter.addAll(blists);
}
}
#Override
public void onLoaderReset(Loader loader) {
Log.i(LOG_TAG, "Testing: onLoaderReset is successfully called");
mAdapter.clear();
}
}
Custom Loader class
package com.example.shara.booklistapp;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
public class BlistLoader extends AsyncTaskLoader<List<Blist>> {
private static final String LOG_TAG = BaseAdapter.class.getName();
private String mUrl;
public BlistLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
Log.i(LOG_TAG, "Testing: onStartLoading is successfully called");
forceLoad();
}
#Override
public List<Blist> loadInBackground() {
Log.i(LOG_TAG, "Testing: loadInBackground is successfully called");
if (mUrl == null) {
return null;
}
List<Blist> blists = null;
try {
blists = BookQueryUtils.fetchBookList(mUrl);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return blists;
}
}
XML that contains the ImageButton
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<EditText
android:id="#+id/search_query_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="#string/hint" />
<ImageButton
android:id="#+id/search_button1"
android:layout_width="42dp"
android:layout_height="42dp"
android:src="#drawable/search" />
</LinearLayout>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:backgroundTint="#color/colorPrimaryDark"
android:backgroundTintMode="add"
android:text="Results" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:dividerHeight="1dp" />
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="#+id/emptytextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="" />
</RelativeLayout>
</LinearLayout>
I want the oncreateloader method to only execute when the search button is clicked and not otherwise.
How can this be achieved? Does my code need heavy modification or is it just something that I missed altogether.
I have previously asked the same question here but I didn't get any answers.
Any help would be greatly appreciated.
Book query utils is for the HTTP request and JSON parsing.
package com.example.shara.booklistapp;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by shara on 12/17/2017.
*/
public final class BookQueryUtils {
public static final String LOG_TAG = BookQueryUtils.class.getName();
private BookQueryUtils() {
}
private static URL createURL(String search_query) throws MalformedURLException {
URL url = null;
String q = "q";
try {
final String base_URL = "https://www.googleapis.com/books/v1/volumes?";
Uri final_Url = Uri.parse(base_URL).buildUpon()
.appendQueryParameter(q, search_query)
.build();
url = new URL(final_Url.toString());
Log.i(LOG_TAG, "The final Url is" + url);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Url could not be formed", e);
}
return url;
}
private static String theHTTPRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection connectionUrl = null;
InputStream theInputStream = null;
try {
connectionUrl = (HttpURLConnection) url.openConnection();
connectionUrl.setReadTimeout(10000);
connectionUrl.setConnectTimeout(15000);
connectionUrl.setRequestMethod("GET");
connectionUrl.connect();
if (connectionUrl.getResponseCode() == 200) {
theInputStream = connectionUrl.getInputStream();
jsonResponse = readFromStream(theInputStream);
} else {
Log.e(LOG_TAG, "could not make the connection");
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem getting the requested data", e);
} finally {
if (connectionUrl != null) {
connectionUrl.disconnect();
}
if (theInputStream != null) {
theInputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder streamoutput = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String urlline = bufferedReader.readLine();
while (urlline != null) {
streamoutput.append(urlline);
urlline = bufferedReader.readLine();
}
return streamoutput.toString();
}
private static List<Blist> extractFeatureFromJSON(String BlistJSON) throws JSONException {
if (TextUtils.isEmpty(BlistJSON)) {
return null;
}
List<Blist> blists = new ArrayList<>();
try {
String a = "";
JSONObject baseJSON = new JSONObject(BlistJSON);
JSONArray items = baseJSON.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
Blist blistss = new Blist();
JSONObject j = items.getJSONObject(i);
JSONObject vInfo = j.getJSONObject("volumeInfo");
if (vInfo.has("authors")) {
JSONArray athrs = vInfo.getJSONArray("authors");
if (athrs.length() != 0) {
for (int k = 0; k < athrs.length(); k++) {
a = athrs.getString(k);
blistss.setAuthor(a);
}
}
}
if (vInfo.has("imageLinks")) {
JSONObject thumbnail = vInfo.getJSONObject("imageLinks");
blistss.setImage(thumbnail.getString("thumbnail"));
}
blistss.setUrl(vInfo.getString("previewLink"));
blistss.setTitle(vInfo.getString("title"));
blistss.setPublisher(vInfo.getString("publisher"));
blists.add(blistss);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Could not parse JSON", e);
}
return blists;
}
public static List<Blist> fetchBookList(String query_url) throws IOException, JSONException {
URL url = createURL(query_url);
String JSONResponse = null;
try {
JSONResponse = theHTTPRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Could not fetch data");
}
List<Blist> blists = extractFeatureFromJSON(JSONResponse);
return blists;
}
}
This is my adapter for the listview.
package com.example.shara.booklistapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by shara on 12/17/2017.
*/
public class ListAdapter extends ArrayAdapter<Blist> {
private ProgressBar progressBar;
public ListAdapter(#NonNull Context context, ArrayList<Blist> blists) {
super(context, 0, blists);
}
public String rslt;
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listitemview = convertView;
if (listitemview == null) {
listitemview = LayoutInflater.from(getContext()).inflate(R.layout.list_layout, parent, false);
}
Blist blist = getItem(position);
ImageView thumbnail = listitemview.findViewById(R.id.thumbnail_imageview);
new imageLoader(thumbnail).execute(blist.getImage());
progressBar = listitemview.findViewById(R.id.Image_Progress_bar);
progressBar.setVisibility(View.GONE);
TextView title = listitemview.findViewById(R.id.title_textview);
title.setText(blist.gettitle());
TextView author = listitemview.findViewById(R.id.author_textview);
author.setText(blist.getauthor());
TextView publisher = listitemview.findViewById(R.id.publisher_texview);
publisher.setText(blist.getpublisher());
return listitemview;
}
private class imageLoader extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public imageLoader(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Updated in Code
Initially set empty query
private String Book_list_request_url = "";
Create method for "Search Click(imagebutton)"
public void Search(View v)
{
Book_list_request_url = editText.getText().toString();
loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
}
Add method to imagebutton
<ImageButton
android:id="#+id/search_button1"
android:layout_width="42dp"
android:layout_height="match_parent"
android:onClick="Search"
android:src="#drawable/ic_launcher_background" />

Android studio project: Images are not lading while fetching from server

I am using this code to download images from my server, but for some reason I cannot display them. I show you the code that I use.
Main activity
MainActivity.java
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://imzzycool.biz.ht/PhotoUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext() {
if (TRACK < arrayImages.length()) {
TRACK++;
showImage();
}
}
private void movePrevious() {
if (TRACK > 0) {
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
Proper xml file used
activity_main.xml
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetch Images"
android:id="#+id/buttonFetchImages" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
android:layout_weight="1"
android:id="#+id/buttonPrev" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_weight="1"
android:id="#+id/buttonNext" />
</LinearLayout>
And the server code(PHP)
getimage.php
<?php
require_once ('dbConnect.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = $_GET['id'];
$sql = "SELECT * FROM photos WHERE id = '$id'";
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: image/jpeg');
echo base64_decode($result['image']);
mysqli_close($con);
} else {
echo "Error";
}
And for get all the images
getAllImages.php
require_once('dbConnect.php');
$sql = "SELECT id FROM photos";
$res = mysqli_query($con, $sql);
$result = array();
$url = "http://imzzycool.biz.ht/PhotoUpload/getImage.php?id=";
while ($row = mysqli_fetch_array($res)) {
array_push($result, array('url' => $url . $row['id']));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
It just replaces image get downloaded but image is not visible

Delete an item in listview inside in an arraylist

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();

My connection between php and android by json not working

I developed an app to connect my android app to remote server and display data in listview.
I did everything but the data doesn't show up in the listview.
These are the files I used to accomplish that, please help me:
MediaActivity.java
package com.shadatv.shada;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Locale;
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.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MediaActivity extends OptionsMenu {
Locale locale;
// boolean mybooks;
Configuration config = new Configuration();
static SharedPreferences sharedPreferenceid;
static SharedPreferences.Editor editorid;
public static final String Myid = "Myid";
String myid = "";
InputStream is = null;
StringBuilder sb = null;
String resultt = "";
JSONArray jArray;
String result = null;
public DAOCanticles cantDatabase = null;
int numberofrowssss;
int responseCode;
String targetcover, targetbname, targetauthname;
public String caNameField = "", caLinkField = "", caImgField = "";
// ///////////////////ONLINE BESTSALED//////////////////////
String caNameJson, caLinkJson, caImgJson;
public ArrayList<String> caNameHolder = new ArrayList<String>();
public ArrayList<String> caLinkHolder = new ArrayList<String>();
public ArrayList<String> caImgHolder = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media);
cantDatabase = new DAOCanticles(this);
new LoadData().execute();
}
// =============================================================================
public void onClickPrograms(View view) {
startActivity(new Intent("com.shadatv.ProgramsActivity"));
}
// =============================================================================
public void onClickCanticles(View view) {
startActivity(new Intent("com.shadatv.CanticlesActivity"));
}
// =============================================================================
public void onClickDocumentaries(View view) {
startActivity(new Intent("com.shadatv.DocumentariesActivity"));
}
// =============================================================================
private class LoadData extends AsyncTask<Void, Void, Void> {
public ProgressDialog progressDialog1;
#Override
protected Void doInBackground(Void... params) {
cantDatabase.deletetable();
getCanticlesByJSON();
addCanticles();
return null;
}
#Override
// can use UI thread here
protected void onPreExecute() {
CharSequence contentTitle = getString(R.string.loading);
this.progressDialog1 = ProgressDialog.show(MediaActivity.this, "",
contentTitle);
}
// -------------------------------------------//
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog1.dismiss();
}
}
// =============================================================================
public void getCanticlesByJSON() {
try {
HttpClient httpclient = new DefaultHttpClient();
try {
} catch (Exception e) {
Log.e("my_log_tag", e.toString());
}
// buffered reader
try {
HttpPost httppost = new HttpPost(
"http://dt-works.com/ags/shadatv/canticles/android_data");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = EntityUtils.toString(entity);
//result = sb.toString();
} catch (Exception e) {
Log.e("my_log_tag", e.toString());
}
try {
result = result.substring(1);
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
caNameJson = json_data.getString("ca_name");
caLinkJson = json_data.getString("ca_link");
caImgJson = json_data.getString("ca_link");
caNameHolder.add(caNameJson);
caLinkHolder.add(caLinkJson);
caImgHolder.add(caImgJson);
}
} catch (JSONException e) {
Log.e("my_log_tag", e.toString());
}
} catch (ParseException e) {
Log.e("my_log_tag", e.toString());
} catch (Exception e) {
Log.e("my_log_tag", e.toString());
}
}
// =============================================================================
public void addCanticles() {
try {
for (int i = 0; i < caNameHolder.size(); i++) {
caNameField = caNameHolder.get(i);
caLinkField = caLinkHolder.get(i);
caImgField = caImgHolder.get(i);
cantDatabase.createCanticle(caNameField, caLinkField,
caImgField);
}
} catch (Exception e) {
Log.e("my_log_tag", "notfilled yet");
}
}
}
CanticlesActivity.java
package com.shadatv.shada;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.zip.ZipInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.SharedPreferences;
import android.database.Cursor;
public class CanticlesActivity extends Activity {
int read;
boolean flage;
final Context context = this;
String picpath="http://img.youtube.com/vi/";
ArrayList<String> getCaName = new ArrayList<String>();
ArrayList<String> getCaLink = new ArrayList<String>();
ArrayList<String> getCaImg = new ArrayList<String>();
String targetCaName;
String targetCaLink;
String targetCaImg;
File sdcard = Environment.getExternalStorageDirectory();
File shadaRoot = new File (sdcard.getAbsolutePath() + "/Shada_Folder");
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bm ;
ImageView img ;
public DAOCanticles cantDatabase =null;
byte[] encoded;
String value;
String useriddd;
//=============================================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
cantDatabase = new DAOCanticles(this);
new LoadData().execute();
}
//=============================================================================
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
CharSequence contentTitle = getString(R.string.loading);
this.progressDialog = ProgressDialog.show(CanticlesActivity.this,"",contentTitle);
}
//-------------------------------------------//
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
showCanticles();
}
//-------------------------------------------//
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
getCanticles();
return null;
}
}
//=============================================================================
public void getCanticles() {
try{
Cursor canticles = cantDatabase.getCanticlesList();
do{
getCaName.add(canticles.getString(0));
getCaLink.add(canticles.getString(1));
getCaImg.add(canticles.getString(2));
}
while(canticles.moveToNext());
}catch(Exception e){
}
}
//=============================================================================
public void Downloadimage(String imgURL) {
try {
String finlpth="";
finlpth=picpath + imgURL + "/2.jpg";
shadaRoot.mkdirs();
URL u = new URL(finlpth);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File DownloadedFile=new File(shadaRoot, imgURL + ".jpg");
// if(!outfile.exists())
FileOutputStream f = new FileOutputStream(DownloadedFile);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
}
//=============================================================================
public void showCanticles()
{
final ListView listview = (ListView) findViewById(R.id.listView1);
for(int i=0; i < getCaName.size(); i++)
{
String caName=getCaName.get(i);
String caLink=getCaLink.get(i);
String caImg=getCaImg.get(i);
Toast.makeText(getBaseContext(), caName, Toast.LENGTH_SHORT).show();
if(!caImg.equalsIgnoreCase("0"))
{
Downloadimage(caLink);
}
}
listview.setOnItemClickListener(new ListView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
long selectedItemId = listview.getSelectedItemId();
ListAdapter adapterr = listview.getAdapter();
String selectedValue = (adapterr.getItem(position)).toString();
String selectedCaName=getCaName.get(position);
String selectedCaLink=getCaLink.get(position);
// // custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.customdialogue);
dialog.setTitle(selectedCaName);
// set the custom dialog components - text, image and button
String selectedbookcover=getCaImg.get(position);
String test= shadaRoot+"/"+ selectedCaName;
String myJpgPath = test+".jpg";
TextView caLink = (TextView) dialog.findViewById(R.id.ca_link);
caLink.setText(selectedCaLink);
options.inSampleSize = 6;
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
dialog.getWindow().setLayout(350,350);
}
});
listview.setAdapter(new DataAdapter(
CanticlesActivity.this,
getCaName.toArray(new String[getCaName.size()]),
getCaLink.toArray(new String[getCaLink.size()]),
getCaImg.toArray(new String[getCaImg.size()])));
}
}
canticles.xml
<?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:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg1"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" >
</ListView>
</LinearLayout>
custom_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:gravity="left"
android:orientation="horizontal"
android:padding="10dip" >
<!-- ListRow Left sied Thumbnail image -->
<ImageView
android:id="#+id/caImgView"
android:layout_width="57dip"
android:layout_height="84dip"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignTop="#+id/linearLayout1"
android:paddingLeft="0dip"
android:scaleType="fitXY"
android:src="#drawable/noimage" />
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="170dip"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/targetmonth1"
android:layout_alignTop="#+id/targetmonth1"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/targetmonth1"
android:orientation="vertical"
android:padding="0dip" >
<TextView
android:id="#+id/caNameView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:text="dddddddd"
android:textColor="#040404"
android:textSize="13dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/caLinkView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/caNameView"
android:layout_alignRight="#+id/caNameView"
android:layout_below="#+id/caNameView"
android:layout_gravity="center_horizontal"
android:text="author"
android:textColor="#343434"
android:textSize="9dip"
android:typeface="sans" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/arrow" />
</RelativeLayout>
use this
public List< String> caNameHolder = new ArrayList< String>();
instead of
public ArrayList< String> caNameHolder = new ArrayList< String>();

Categories